C#-尝试将用户输入解析为int时出现错误 [英] C#- Getting error when trying to parse user input to int

查看:93
本文介绍了C#-尝试将用户输入解析为int时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我无法弄清楚为什么我在运行此方法时总是收到未处理FormatException"错误:

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?

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

**I was running the program on Microsoft Visual C# 2010 Express as a console application.

推荐答案

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

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.

您可以通过切换到 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将返回false.上面的代码将使程序不断提示用户,直到他们输入有效的数字,而不是提高FormatException.

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.

这篇关于C#-尝试将用户输入解析为int时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆