I've started to program somewhat of a backpack. You are supposed to store items in it, ask it what items I've stored and clear the items. I have done pretty well but got stuck on an annoying detail. The menu has options 1 to 4 with 4 being the closing of the program. In my switch statement I got these 4 cases and they are working perfectly. In the default statement I am simply telling the user "wrong menu choice" if you press for example a 5.
Here's the questions. If i press say an A the program crashes. I want letters to also trigger the default. How do I do that?
Here is the code: (I dont expect you to understand the swedish words inside the code :))
internal class Program
{
static void Main(string[] args)
{
bool minBool = true;
string foreMal = null;
while (minBool)
{
Console.WriteLine("Välkommen till ryggsäcken. Vad vill du göra?: ");
Console.WriteLine("[1] Lägg till ett föremål");
Console.WriteLine("[2] Skriv ut innehållet");
Console.WriteLine("[3] Rensa innehållet");
Console.WriteLine("[4] Avsluta");
int input = Int32.Parse(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("Var god ange ett föremål");
foreMal = Console.ReadLine();
break;
case 2:
Console.WriteLine("Ryggsäcken innehåller: " " " foreMal);
break;
case 3:
Console.WriteLine("Ryggsäcken rensas");
foreMal = "";
break;
case 4:
minBool = false;
break;
default:
Console.WriteLine("Felaktigt menyval");
break;
}
CodePudding user response:
Instead of:
int input = Int32.Parse(Console.ReadLine())
Use:
if (!int.TryParse(Console.ReadLine(), out var input))
{
Console.WriteLine("Bad input"); // change output as you'd like, of course
continue;
}
This will prevent an exception when you try to parse the input.
CodePudding user response:
First off, when looking for help from other developers, please don't just use terms like crashes. A good developer knows to provide details (is there a compiler error, do you know which line fails, etc.). Crashes is a non-technical term that offers no troubleshooting information.
Looking at your code, this line is almost certainly your problem:
int input = Int32.Parse(Console.ReadLine());
This line converts a string to a int
. However, it throws an exception if the string cannot be converted to an int
. For example, "A"
cannot be converted to an int
.
You have a couple of options here. First, you can do as was suggested elsewhere and keep the user input as a string. You will need to modify your switch
statement to test for string values instead of integer values.
The other alternative is to use int.TryParse()
instead of int.Parse()
. int.TryParse()
will return a value that indicates if the string could be converted. It does not throw an exception in this case. So you can try to parse it to an integer, and if that fails you can perform other tests, such as whatever function "A"
is supposed to accomplish.