I am new to c#, and I can’t figure out why I keep getting a ‘FormatException was unhandled’ error when I run this method:
public void bet()
{
int betAmount;
Console.WriteLine("How much would you like to bet?");
betAmount = int.Parse(Console.ReadLine());
Console.WriteLine(_chips - betAmount);
}
The program does not stop to wait for user input, and I don’t know why this is?
What can I do to get the program to wait for the user’s input in this method?
**I was running the program on Microsoft Visual C# 2010 Express as a console application.
You need to handle the case where
Console.ReadLine()returns something that is not an integer value. In your case, you’re probably getting that error because something is typed incorrectly.You can solve this by switching to TryParse:
int.TryParsewill return false if the user types something other than an integer. The above code will cause the program to continually re-prompt the user until they enter a valid number instead of raising theFormatException.This is a common problem – any time you are parsing user generated input, you need to make sure the input was entered in a proper format. This can be done via exception handling, or via custom logic (as above) to handle improper input. Never trust a user to enter values correctly.