I'm doing some school work and would just like to be pointed in the right direction. I am creating a Hotel project which books people in and also books them out when leaving. I'm struggling on a certain part which asks which room you need vacating and then puts a 0 into this position in the array. I am not going to beat around the bush i don't know where to start. This is my code so far.
using System;
namespace Task7_2
{
class Motel
{
int[] rooms;
const int MAX = 21;
int roomNumber, guests, vacate;
static void Main()
{
Motel BatesMotel = new Motel();
BatesMotel.runMotel();
BatesMotel.showAllRooms();
}
//*******************************************************
public Motel()
{
rooms = new int[MAX + 1]; // allow rooms from 1 to MAX
}
//******************************************************
public void runMotel()
{
string choice = "";
do
{
Console.Clear();
Console.WriteLine("The Bates Motel");
Console.WriteLine("===============");
Console.WriteLine("1. Book a room");
Console.WriteLine("2. Vacate a room");
Console.WriteLine("3. Display ALL Room Details");
Console.WriteLine("4. Vacate ALL rooms");
Console.WriteLine("5. Quit");
Console.Write("Enter your choice : ");
choice = Console.ReadLine();
if (choice == "1")
{
bookRoom();
}
else if (choice == "3")
{
showAllRooms();
}
else if (choice == "2")
{
vacateOneRoom();
}
}
while (choice != "5");
}
//*******************************************************
public void bookRoom()
{
Console.WriteLine("\nThe Bates Motel");
Console.WriteLine("===============");
Console.WriteLine("Book a room");
Console.Write("Enter the room number : ");
roomNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("How many guests : ");
guests = Convert.ToInt32(Console.ReadLine());
rooms[roomNumber] = guests; // make the booking
Console.WriteLine("Room " + roomNumber + " booked for " + guests + " people");
}
//*******************************************************
public void showAllRooms()
{
for (int i = 1; i < MAX; i++)
{
Console.Write("Room " + (i )+"\t\t\t" + rooms[i] + " guests \n" );
}
Console.ReadLine();
}
public void vacateOneRoom()
{
Console.WriteLine("Which room is being vacated");
Console.ReadLine();
}
}
}
using System.Collections.Generic;
List<int> myList= new List<int>();
int num = 22;
myList.Add(num);
myList.Remove(num); //removes matching item
myList.Add(33);
myList.RemoveAt(0); //removes at array index
bool[] barray = new bool[number_of_rooms];
When someone booked a particular room then
barray[room_number]=true;
When someone vacate a particular room then
barray[room_number]=false;
checking
for(int i=0;i<barray.lenght;i++)
{
if(barray[i]==true)
Console.WriteLine("Room number"+300+i+"is not free");
else
Console.WriteLine("Room number"+300+i+"is free");
}
example output:::
Room number 300 is not free
Room number 301 is not free
Room number 302 is free
Room number 303 is not free
Room number 304 is free
Related
I just finished a programming 1 class and the last assignment I was making was named "the buss" where I was supposed to identify the different passengers on the buss. Sort the by age, count the average age on the buss and so on. But there were some things I didn't figure out in time and trying to do it now and was looking is someone could help me.
My problem is that I'm supposed to identify their sex and I just can't figure out how to make that.
The second one is to "poke them" and based on different age and sex make different comments.
using System;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
namespace Bussen
{
class Buss
{
//passagerare means passenger
public int[] passagerare = new int[25];
public int antal_passagerare;
public void Run()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Welcome to the awesome Buss-simulator");
int menu;
do
{
//the menu of every choise you can make.
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Välj ett alternativ: ");
Console.WriteLine("1. Lägg till en passagerare. ");
Console.WriteLine("2. Kontrollera åldern på passagerarna. ");
Console.WriteLine("3. Beräkna den sammanlagda åldern på passagerarna. ");
Console.WriteLine("4. Beräkna medelåldern på passagerarna. ");
Console.WriteLine("5. Identifiera den äldsta passageraren. ");
Console.WriteLine("6. Hitta åldern. ");
Console.WriteLine("7. Sortera bussen efter ålder. ");
Console.WriteLine("8. Print sex. ");
Console.WriteLine("0. Avsluta programmet. ");
menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
add_passenger();
break;
case 2:
Print_buss();
break;
case 3:
Calc_total_age();
break;
case 4:
Calc_average_age();
break;
case 5:
Max_age();
break;
case 6:
Find_age();
break;
case 7:
Sort_buss();
break;
case 8:
Print_sex();
break;
case 0:
menu = 0;
break;
}
} while (menu != 0);
}
//where you add you passengers by age
public void add_passenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill lägga till.");
string str1 = Console.ReadLine();
int size = Convert.ToInt32(str1);
for (int i = 0; i < size; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Lägg till en passagerare genom att skriva in personens ålder ålder: ");
string answer = Console.ReadLine();
int nya_passagerare = Convert.ToInt32(answer);
passagerare[i] = nya_passagerare;
antal_passagerare++;
}
}
// this is where you print out all the passengers.
public void Print_buss()
{
for (int i = 0; i < antal_passagerare; i++)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("Passagerarnas ålder är: " + passagerare[i]);
}
}
//this is where you add the total age on every passenger.
public void Calc_total_age()
{
int sum = 0;
for (int i = 0; i < passagerare.Length; i++)
{
sum += passagerare[i];
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Den sammanlagda åldern på passagerarna är " + sum + ".");
}
//where you calculate the average age on the buss
public void Calc_average_age()
{
int sum = 0;
for (int i = 0; i < antal_passagerare; i++)
{
sum += passagerare[i];
}
double dsum = Convert.ToDouble(sum);
double dsum1 = dsum / antal_passagerare;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Passagerarnas medelålder är " + dsum1 + " år.");
Console.WriteLine(" ");
}
//where you find the oldest passenger on the buss
public void Max_age()
{
int maxAge = passagerare[0];
foreach (var enPassagerare in passagerare)
if (enPassagerare > maxAge)
maxAge = enPassagerare;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Den äldsta passageraren är " + maxAge + " år gammal.");
}
//this where you find with seat the diffent passengers sitt on between surtn ages
public void Find_age()
{
bool found = false;
Console.WriteLine("Vilken är den yngst åldern som du vill hitta ?");
int yngst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vilken är det högst åldern som du vill hitta ?");
int högst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Passagerarna som mellan åldern " + yngst + " - " + högst + " sitter i : ");
for (int i = 0; i < passagerare.Length; i++)
{
if (passagerare[i] > högst || passagerare[i] > yngst)
{
Console.WriteLine("stolen " + i);
found = true;
}
}
if(!found)
{
Console.WriteLine("OBS det finns inte sån ålder i bussen ");
}
}
//this is where you sort the buss from ungest to oldest passenger
public void Sort_buss()
{
int temp;
for (int i = 0; i < passagerare.Length - 1; i++)
{
for (int j = 0; j < passagerare.Length - 1 - i; j++)
{
if (passagerare[j] > passagerare[j + 1])
{
temp = passagerare[j];
passagerare[j] = passagerare[j + 1];
passagerare[j + 1] = temp;
}
}
}
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("Passagerare " + (i + 1) + " är " + passagerare[i] + " år gammal ");
}
}
//this is where im supose to identify with sex every passenger has...
public void Print_sex()
{
for (int k = 0; k < info.Length +1; k++)
{
Console.WriteLine("Plats" + info[k] + kön);
}
}
class Program
{
public static void Main(string[] args)
{
var minbuss = new Buss();
minbuss.Run();
var mysex = new sex();
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
}
Like others have suggested, the best way to do this is to refactor (change) your code to use classes. This is called object oriented programming. I'll try my best to explain it for your current level of experience.
Firstly, create a class. Let's call this "Person".
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
Secondly, let's create a list to hold the people on the bus. Instead of creating an array with a set size, we'll create a List.
List<Person> People = new List<Person>();
Now, in your "add_passenger" method, which I advise you rename to follow the general coding standards, to "AddPassenger".
public void AddPassenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill läggatill.");
// Let's presume the input is in the format Name, Age, Sex.
string input = Console.ReadLine();
// This will create a string array with all the "details".
// E.g [0] = Name, [1] = Age, Sex [2].
string[] personDetails = input.Split(",");
// Instantiate a person object and populate the properties.
Person person = new Person();
person.Name = personDetails[0].Trim();
person.Age = Convert.ToInt32(personDetails[1].Trim());
person.Sex = personDetails[2].Trim();
// Add the newly created person to the people list.
People.Add(person);
}
Now you're probably thinking that your bus can a very large amount of people, which is right because a List can hold a couple billion items - that's a pretty big bus! I would advise to add a method that checks the count is less than 25 before the AddPassenger() method call within your switch statement.
I would also like to advise that C# has an incredibly powerful ability to do searches within lists and can even perform mathematical calculations for you in one liners using something called LINQ. An example of this from your sample code would be your "Calc_total_age" method - which I would rename to CalculateTotalAge (it's better to be specific what a function does than to abbreviate. This helps other developers working on your code understand what it's doing if it's clear.
public void CalculateTotalAge()
{
Console.ForegroundColor = ConsoleColor.Red;
// Calculate the total age using a LINQ expression.
int totalAge = People.Sum(x => x.Age);
Console.WriteLine($"Den sammanlagda åldern på passagerarna är {totalAge}");
}
Finally, to answer your question about listing the age of every person on the bus, we can do the following.
public void ListSexOfEveryPerson()
{
foreach(Person person in people)
{
Console.WriteLine($"{person.Name}'s sex is {person.Sex}");
}
}
If we wanted to get creative and use LINQ expressions, we could do:
public void ListSexOfEveryPerson()
{
people.ForEach(p => Console.WriteLine($"{p.Name}'s sex is {p.Sex}"));
}
If LINQ expressions are confusing at this time, then just use the first example until you feel comfortable, there's nothing wrong with a foreach loop!
Also, if you're wondering what the '$' symbol before the quotation is used for, it's for string interpolation. It's a better way of 'injecting' values into a string instead of doing "X" + "X" + "X".
Hope this helps!
essentially I'm making a guessing game for an assignment but as I try to output the list it comes out as
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
essentially I just need to store a users guess number and their attempt number so that once they guess the correct number it will display it as
"YOU WON, the number was ___ and here are your attempts
you chose 45
you chose 54
you chose 32
you chose ___
using System;
using System.Collections.Generic;
namespace main__4_8_2021_
{
class Program
{
public static void Main(string[] args)
{
while (true)
try
{
int NumberOfTries = 0;
Console.WriteLine("Guess a number between 1 and 100");
int number = Convert.ToInt32(Console.ReadLine());
List<int> mylist2 = new List<int>(number);
List<int> mylist = new List<int>(NumberOfTries);
int rng = new Random().Next(1, 101);
if (number == rng)
{
Console.WriteLine("Your guess was correct! The number was " + number + "!");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
break;
}
else if (number > rng)
{
NumberOfTries++;
Console.WriteLine("Your guess was too high ");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
Console.WriteLine("you now have done " + NumberOfTries + " Tries");
}
else if (number < rng)
{
NumberOfTries++;
Console.WriteLine("too low, ");
Console.WriteLine(mylist);
Console.WriteLine(mylist2);
Console.WriteLine("you now have done " + NumberOfTries + " Tries");
}
Console.Write($"Try again. ");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
(the other console.writelines of the lists are just there for debug)
You have a number of issues with your code.
First, you don't need a counter for number of attempts, a Count property on the List is enough.
Second, you need to keep that list outside of the loop so it is not recreated each time.
Try the below
using System;
using System.Collections.Generic;
namespace main__4_8_2021_
{
class Program
{
public static void Main(string[] args)
{
List<int> mylist = new List<int>();
void PrintListContents() {
Console.WriteLine("here are your attempts");
var index = 0;
foreach(var value in mylist) {
Console.WriteLine($"{index}. You chose {value}");
index++;
}
}
while (true)
try
{
Console.WriteLine("Guess a number between 1 and 100");
int number = Convert.ToInt32(Console.ReadLine());
mylist.Add(number);
int rng = new Random().Next(1, 101);
if (number == rng)
{
Console.WriteLine("Your guess was correct! The number was " + number + "!");
PrintListContents()
break;
}
else if (number > rng)
{
NumberOfTries++;
Console.WriteLine("Your guess was too high ");
PrintListContents()
Console.WriteLine("you now have done " + myList.Count + " Tries");
}
else if (number < rng)
{
NumberOfTries++;
Console.WriteLine("too low, ");
PrintListContents()
Console.WriteLine("you now have done " + myList.Count + " Tries");
}
Console.Write($"Try again. ");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Console.WriteLine(mylist);
If value is null, only the line terminator is written. Otherwise, the
ToString method of value is called to produce its string
representation, and the resulting string is written to the standard
output stream.
SOURCE https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-5.0#System_Console_WriteLine_System_Object_
this means that you actually calling the ToString method of the list. Most of the "complex" types do not overwrite the ToString method which results in just returning the string representation of Type. In your case: List<int> which is represented as System.Collections.Generic.List`1[System.Int32]
you may also want to have a look at https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-5.0
Need to get it to loop after the user presses "r" at this part, need it to do as it says in the Console.WriteLine and redo all the questions
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
using System;
namespace ConsoleApp1
{
class Program
{
static int iNum1;
static int iNum2;
static int numOfCorrect;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Ten Question Multiplication Quiz");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Instructions");
Console.WriteLine("This program will give you 10 questions on multiplication for you to answer, after answering the ten questions it will display how many you got right!");
Console.WriteLine("If you decide to retry the quiz it will have 10 completely different questions! So be prepared for a challenge.");
Console.ResetColor();
Console.WriteLine("Press Enter to Start");
Console.ReadKey();
Console.Clear();
Random rRandom = new Random();
for (int loop = 0; loop < 10; loop++)
{
int userAnswer;
int answer;
iNum1 = rRandom.Next(11);
iNum2 = rRandom.Next(11);
{
Console.Write("What is " + iNum1 + " times " + iNum2 + "? ");
answer = iNum1 * iNum2;
userAnswer = Convert.ToInt32(Console.ReadLine());
}
if (answer == userAnswer)
{
Console.WriteLine(userAnswer + " is correct ");
numOfCorrect++;
Console.Clear();
}
else
{
Console.WriteLine(userAnswer + " is incorrect ");
Console.Clear();
}
if (userAnswer > 100)
{
loop += (loop - 1);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("That number is too high, try again");
}
}
{
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
else if (Console.ReadKey().Key != ConsoleKey.C)
System.Environment.Exit(0);
}
}
}
}
You can either capsulate your whole code inside another loop like pawel stated in his comment. Or you could also create a recursive function call like:
static void Main(string[] args)
{
Quiz();
}
void Quiz(){
// Initialize stuff
// Display stuff
for(int loop = 0; loop < 10; loop++)
{
// Question User
// Evaluate Answers
// and so on
// Check user input for retry
if (Console.ReadKey().Key != ConsoleKey.R)
{
Console.Clear();
Quiz(); // <---- Calls the same method again
}
}
}
So I'm trying to create a dartgame in Console Application with C#.
This is as far as I have gotten atm:
class Program
{
static void Main(string[] args)
{
Game gameOn = new Game();
gameOn.PlayGame();
}
class Game
{
private List<Players> playerList = new List<Players>();
public void AddPlayers(string name)
{
Players names = new Players(name);
playerList.Add(names);
}
public void PlayGame()
{
Console.WriteLine("Välkommen till Dartspelet! Tryck valfri knapp för att fortsätta...");
Console.ReadLine();
Console.WriteLine("Skriv in antal spelare. Ni kommer också att möta en Dator.");
Console.WriteLine();
int players = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < players; i++)
{
Console.Write("Skriv in spelarens namn: ");
string playersNames = Console.ReadLine();
AddPlayers(playersNames);
}
Console.WriteLine();
Console.WriteLine("Spelet har börjat!");
Console.WriteLine();
foreach (Players name in playerList)
{
Console.WriteLine("Datorn börjar att kasta... Var god vänta...");
System.Threading.Thread.Sleep(2000);
Random rng = new Random();
int ranAttempt1 = rng.Next(0, 21);
int ranAttempt2 = rng.Next(0, 21);
int ranAttempt3 = rng.Next(0, 21);
Attempts result = new Attempts(ranAttempt1, ranAttempt2, ranAttempt3);
Console.WriteLine("Datorn Fick " + result.GetScore() + " på 3 kast.");
Console.ReadLine();
Console.WriteLine(name + "s Tur! ");
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 1:");
int attempt1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 2:");
int attempt2 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 3:");
int attempt3 = Int32.Parse(Console.ReadLine());
Attempts result1 = new Attempts(attempt1, attempt2, attempt3);
Console.WriteLine(name + " Fick " + result1.GetScore());
}
Console.ReadLine();
}
}
class Attempts
{
private int attempt1;
private int attempt2;
private int attempt3;
public Attempts(int attempt1 = 0, int attempt2 = 0, int attempt3 = 0)
{
this.attempt1 = attempt1;
this.attempt2 = attempt2;
this.attempt3 = attempt3;
}
public int GetScore()
{
return attempt1 + attempt2 + attempt3;
}
}
class Players
{
private string Name { get; set; }
public List<Attempts> attempts = new List<Attempts>();
public Players(string name = "")
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
}
I need help with creating a while loop around the foreach loop that will end when one of the players has reached a score of 301 or over. I also need a method to keep the score in a List or something like that for every turn. But yeah I'm stuck so any help is greatly appriciated! :)
And sorry if the code is a bit messy
Thanks in advance!
Well, you already have the List for the player's attempts. You could:
add a while loop around the foreach(Players...):
append the attempt after it's finished.
after a each player's attempts, calculate the total score.
print the score and exit if the total score > 301
while(true)
{
foreach(Players name in playerList)
{
// existing code here
// you should encapsulate attempts with getter and setter,
// but according to your Players class this will work.
name.attempts.add(result1);
// now sum up the total results for the player
// exercise for the reader.
int totalResults = player.getTotalScore();
if(totalResults > 301)
{
Console.WriteLine("Player " + name.getName() + " won the game!");
Environment.exit(0);
}
}
}
I am very new to C# and I would like to print out the contents of a list so that the information stored in seatsBooked will be displayed for the user if they pick the number 3 case of my switch statement. My code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AirlineReservation
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
bool[] seats = new bool[10];
//To keep a separate list of seats taken
List<int> seatsBooked = new List<int>();
int inputI = 0;
char inputC = ' ';
bool quit = false;
do
{
Console.Clear();
int assignSeat = rand.Next(5, 10);
Console.WriteLine("Thanks for flying with Steve-O Airlines" + "\n" + '\n' +
"\nPlease enter the number one [1] for First Class" +
" \nPlease enter the number two [2] for Economy" +
"\nPlease enter the number three [3] for seats taken" +
"\nPlease enter the number four [4] to exit the order system");
inputI = Int32.Parse(Console.ReadLine());
switch (inputI)
{
case 1: //is the seat booked, if not book it
int assignedSeat;
if (seatsBooked.Count == 0)
{
assignedSeat = rand.Next(0, 5);
seats[assignedSeat] = true;
seatsBooked.Add(assignedSeat);
}
else
{
do //while there are available seats and current seat has not being assigned before.
{
assignedSeat = rand.Next(0, 5);
if (!seatsBooked.Contains(assignedSeat)) //if assignedSeat is not booked.
{
seats[assignedSeat] = true;
}
//repeat while the random seat number is already booked and there are avaialable seats
} while (seatsBooked.Contains(assignedSeat) && seatsBooked.Count < 5);
if (seatsBooked.Count < 5) //if seatsBooked list is not full for First Class
{
seatsBooked.Add(assignedSeat); //Add current random-generated seat to the list.
}
}
if (seatsBooked.Count >= 5)
{
Console.WriteLine("All seats for First Class are booked! Looks like a bad lunch for you.");
Console.WriteLine("Press enter to continue...");
}
else
{
Console.WriteLine("Your seat number is: {0}" + " \nNow pay me $550", assignedSeat + 1);
Console.WriteLine("Press enter to continue...");
}
Console.ReadLine();
break;
case 2:
seats[assignSeat] = true;
Console.WriteLine("Your seat number is: {0}"+ " \nNow pay me $350", assignSeat + 1);
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
break;
case 3:
Console.WriteLine(seatsBooked);
break;
case 4:
quit = true;
break;
default:
Console.WriteLine("ERROR::INVALID SELECTION" +
"\nYou will not get a flight this way!" );
quit = true;
break;
}
} while (!quit);
}
}
}
You can't just print a list out like that... what ends up happening is ToString() is called on your collection, and you get the fully qualified name of your class instead of a list of numbers.
You can create a string, however, which will print correctly. Something like this should work:
Console.WriteLine(string.Join(", ", seatsBooked)); // concatenate elements with comma
If your list consists of the numbers 1 thru 5, your output would be:
1, 2, 3, 4, 5
As you have probably discovered Console.WriteLine(seatsBooked); will not show you the contents of the list. One way to do that is a foreach loop. The simplest form would look like this.
foreach(int seatBooked in seatsBooked) {
Console.WriteLine(seatBooked);
}