C# - 尝试将用户输入解析为int时出错

Ato*_*mix 1 c# parsing user-input

我是c#的新手,当我运行这个方法时,我无法弄清楚为什么我一直得到'FormatException is unhandled'错误:

public void bet()
{
    int betAmount;

    Console.WriteLine("How much would you like to bet?");
    betAmount = int.Parse(Console.ReadLine());
    Console.WriteLine(_chips - betAmount);
} 
Run Code Online (Sandbox Code Playgroud)

程序不会停止等待用户输入,我不知道为什么会这样?

如何让程序在此方法中等待用户的输入?

**我在Microsoft Visual C#2010 Express上运行该程序作为控制台应用程序.

Ree*_*sey 7

您需要处理Console.ReadLine()返回非整数值的情况.在您的情况下,您可能会收到该错误,因为输入的内容不正确.

你可以通过切换到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);
} 
Run Code Online (Sandbox Code Playgroud)

int.TryParse如果用户键入除整数之外的其他内容,则返回false.上面的代码将导致程序不断重新提示用户,直到他们输入有效数字而不是提高FormatException.

这是一个常见问题 - 每次解析用户生成的输入时,都需要确保以正确的格式输入输入.这可以通过异常处理或通过自定义逻辑(如上所述)来处理不正确的输入.永远不要相信用户正确输入值.