C
C#3y ago
maroonlol

❔ My code repeats my menu everytime a invalid character is added - i want to display a error message

My menu works but I want to display a error message if the user enters a invalid character. I was thinking of adding a else statement but that would just display Invalid try again even if it is right aswell. I'm unsure where to put this in a repeating while loop https://github.com/AbdulRaheemNazir/Mini-Apps-Working/blob/main/Menu%20Help Code here
2 Replies
mtreit
mtreit3y ago
I would probably do something like this:
while (true)
{
Console.WriteLine("Select an option.");
Console.WriteLine("1) Do something");
Console.WriteLine("2) Do something else");
Console.WriteLine("3) Quit");

var choice = Console.ReadKey().KeyChar;
Console.WriteLine();
Console.WriteLine($"You chose {choice}.");
Console.WriteLine();

if (choice == '3')
{
break;
}

switch (choice)
{
case '1':
Console.WriteLine("Something.");
break;
case '2':
Console.WriteLine("Something else.");
break;
default:
Console.WriteLine("Invalid, try again.");
break;
}

Console.WriteLine();
}

Console.WriteLine("Done.");
while (true)
{
Console.WriteLine("Select an option.");
Console.WriteLine("1) Do something");
Console.WriteLine("2) Do something else");
Console.WriteLine("3) Quit");

var choice = Console.ReadKey().KeyChar;
Console.WriteLine();
Console.WriteLine($"You chose {choice}.");
Console.WriteLine();

if (choice == '3')
{
break;
}

switch (choice)
{
case '1':
Console.WriteLine("Something.");
break;
case '2':
Console.WriteLine("Something else.");
break;
default:
Console.WriteLine("Invalid, try again.");
break;
}

Console.WriteLine();
}

Console.WriteLine("Done.");
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server