Print out contents of a list human readable C# - c#

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);
}

Related

how to output the contents of the list

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

Stop program from crashing when pressing Enter

So, today I decided to start learning C# from scratch. I've managed to make a little math problems program. The thing is, whenever the user just presses enter without entering a value (or anything which isn't a number), the program crashes. I've read something about TryParse but I just can't get it.
Here's my code (part of it):
{
Random numberGenerator = new Random();
int num01 = numberGenerator.Next(1, 20);
int num02 = numberGenerator.Next(1, 20);
Console.WriteLine("Welcome, user.");
Console.ReadKey();
Fail2:
Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");
int res1 = Convert.ToInt32(Console.ReadLine());
if (res1 == num01*num02)
{
Console.WriteLine("Your answer is correct");
Console.ReadKey();
}
else
{
goto Fail;
}
Thanks in advance!
Hello & welcome to StackOverflow! I have a couple of suggestions:
Avoid using goto
Replace all your Convert.X with X.TryParse whenever it's the user who gives you the value, since you don't know what it could be
Random numberGenerator = new Random();
int num01 = numberGenerator.Next(1, 20);
int num02 = numberGenerator.Next(1, 20);
Console.WriteLine("Welcome, user.");
Console.ReadKey();
// Always use a loop instead of goto statements!
while (true)
{
Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");
// Old line: int res1 = Convert.ToInt32(Console.ReadLine());
// Problem: this assumes that Console.ReadLine() returns a valid number, e.g. "3"
// but as you said, the user can trick you and put something else
if (!int.TryParse(Console.ReadLine(), out int res1))
continue; // This will rerun the loop from the top, so the user will need to re-write a response
if (res1 == num01*num02)
{
Console.WriteLine("Your answer is correct");
Console.ReadKey();
}
else
{
break; // stop the outer loop on top
}
}
Use int.TryParse like this...
int res1 = 0;
if (!int.TryParse(Console.ReadLine(), out res1))
{
//failed;
}
if (res1 == num01*num02)
...
https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netcore-3.1

Random Number generator fail

How do I get the program to loop back around from the beginning if the incorrect number is picked? I'm not sure what I'm doing wrong. I tried ifs, do whiles, whiles, and if elses:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayProblms
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10: ");
RandomNumberGenerator();
Console.ReadLine();
}
public static void RandomNumberGenerator()
{
Random rand = new Random();
int userValue = int.Parse(Console.ReadLine());
int randValue = rand.Next(1, 11);
int attempts = 0;
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
}
while (userValue != randValue)
{
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
break;
}
}
}
}
You should put int userValue = int.Parse(Console.ReadLine()); inside the loop and check input on every iteration. break must be only if userValue == randValue:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
while (true)
{
int userValue = int.Parse(Console.ReadLine()); // input inside the loop
if (userValue == randValue) // checking inside the loop
{
Console.WriteLine("You have guessed correctly!");
break;
}
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
}
I would use do...while to continue asking user to enter the new number until he guessed correctly.
Example below:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
// do...while cycle to ask user to enter new value each time the used has been wrong
do
{
// read user input
int userValue = int.Parse(Console.ReadLine());
// if user guessed correct
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
// go away from do...while loop
// it will stop asking user and will exit from the method
break;
}
// if user has been wrong
Console.WriteLine("You have guessed incorrectly");
// increment attempts count
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
// and repeat until user guessed correctly
while(userValue != randValue)
}
You're on the right track, but you need to put the Console.ReadLine inside a while loop and break out of the loop only when the user's value matches.
Something like this pseudo code:
Generate random number
while (true) {
Get value from user
If it matches, break
}

How can I make a program loop back to the start if else is true? C#

Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
Thanks for the help!
You can do this instead
User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0)
{
Console.WriteLine("Sorry you input an invalid number. ");
User = Convert.ToInt32(Console.ReadLine());
}
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}

C# Console Program Loop Issue

I have tried to create a C# program that gives the user 3 options:
Create name (gets the user to enter their first name and surname and display it as J.Blogg)
Factorial of a number (outputs as for example 5x4x3x2x1 =120 which is the factorial of 5
Quit
I have the program work fine but when I try picking option 1 (create name) and then option 2 it goes to option 1 instead and then it doesn't lets me Quit (option 3).
I'm new to programming so it could be simple but I can't see where i'm going wrong,
Any help would be very greatful.
I want to keep the same layout, I think my problem could be the loops but any help and improvement would be great.
static void Main(string[] args)
{
//The value returned from the topmenu method is stored in a variable called useroption
int useroption;
useroption = topmenu();
// excute while loop untill option is not 1-3
do
{
if (useroption == 1)
{
Console.Clear();
Createname();
//break;
}
if (useroption == 2)
{
Console.Clear();
factorial();
// break;
}
if (useroption == 3)
{
Console.Clear();
Console.WriteLine("Thank you for using my program, Good bye !!!");
// break;
}
//topmenu();
}
while (useroption != 3);
Console.ReadKey();
}
//This method present the user with an menu which the user has a choice of 3 options
static int topmenu()
{
int option;
string option_str;
Console.Clear();
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********* OPTION 1 : Enter your name *********");
Console.WriteLine("********* OPTION 2 : Enter the number you want to factorise *********");
Console.WriteLine("********* OPTION 3 : Quit *********");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
option_str = Console.ReadLine();
option = Convert.ToInt32(option_str);
Console.Clear();
if (option < 0 || option > 3)
{
Console.WriteLine("You have enter an invald option,");
Console.WriteLine("Please chose a option between 1-3 (Please press any key to return to main menu)");
Console.ReadLine();
Console.Clear();
topmenu();
}
else
{
Console.WriteLine("You have chosen option: " + option + " (Please press any key continue)");
}
Console.ReadKey();
return option;
}
//this method asks user to enter their name (1st name then surname) and presents it back to the user as their intial(1st name) and surname
static void Createname()
{
string firstname, surname, firstname_str, surname_str, userfullname;
Console.Clear();
Console.WriteLine("Please enter your first name ");
firstname_str = Console.ReadLine();
firstname = Convert.ToString(firstname_str);
Console.Clear();
Console.WriteLine("Please enter your surname name ");
surname_str = Console.ReadLine();
surname = Convert.ToString(surname_str);
Console.Clear();
userfullname = firstname + surname;
Console.WriteLine("You have entered your name as " + firstname[0] + "." + surname);
Console.WriteLine("(Please press any key to return to main menu)");
Console.ReadKey();
topmenu();
}
//this method asks the user to enter a number and returns the factorial of that number
static double factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
Console.Clear();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i + " * ");
}
Console.WriteLine("= "+factorial+ " which is factorial of " + number_str.ToString() );
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
}
}
Just put these line inside do...while
int useroption;
useroption = topmenu();
rearrange as following...
int useroption;
// excute while loop untill option is not 1-3
do
{
useroption = topmenu();
and your program will work fine
The full code is here : http://pastebin.com/fCh0ttUY
First of al, set useroption to 0 after executing some code. Otherwise it will keep executing it.
Second, ReadKey() right before your while statement. Otherwise you won't be able to read the input.
The issue is that although you display topmenu again you never re-assign the value of useroption.
As gypsyCoder said, moving the display of your menu inside the do{}while() block will fix your issue because it will cause the useroption to be re-assigned each time round the loop.

Categories

Resources