开发者

C#- Getting error when trying to parse user input to int

开发者 https://www.devze.com 2023-01-15 22:27 出处:网络
I am new to c#, and I can\'开发者_如何学Got figure out why I keep getting a \'FormatException was unhandled\' error when I run this method:

I am new to c#, and I can'开发者_如何学Got 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:

public void bet()
{
    int betAmount;

    Console.WriteLine("How much would you like to bet?");
    while(!int.TryParse(Console.ReadLine(), out betAmount))
    {
        Console.WriteLine("Please enter a valid number.");
        Console.WriteLine();
        Console.WriteLine("How much would you like to bet?");
    }

    Console.WriteLine(_chips - betAmount);
} 

int.TryParse will 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 the FormatException.

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.


Are you using Visual Studio? Some other IDEs may by default run console apps in a non-interactive mode. For example I know that in MonoDevelop you have to specifically change the project properties so that the program runs in an external console if you want to do that.


Might be better and more bulletproof to do a regex against the input for digits such as for example:

public static Regex NumInpRegex = new Regex(
      "^(?<inp_num>\\d+)$",
    RegexOptions.IgnoreCase
    | RegexOptions.Singleline
    | RegexOptions.ExplicitCapture
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );
string InputText = Console.ReadLine();
Match m = NumInpRegex.Match(InputText);
if (m.Success && InputText.Length > 0){
    betAmount = int.Parse(m.Groups["inp_num"].Value);
    Console.WriteLine(_chips - betAmount);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消