2

我想检查用户的输入是否是数字。如果是,我希望该功能继续运行,否则想提醒他并再次运行它。

Console.WriteLine(String.Concat("choose your action" ,Environment.NewLine ,
                                "1.Deposit", Environment.NewLine,
                                "2.Withdraw", Environment.NewLine,
                                "3.CheckAccount"));
string c = Console.ReadLine();
int value = Convert.ToInt32(c);

if (value==char.IsLetterOrDigit(value)) //<----- no good why?
{
    switch (value)
    {
        case 1:
            Deposit();
            return;
        case 2:
            Withdraw();
            return;
        case 3:
            CheckAccount();
            return;
    }
}
4

2 回答 2

15

只需使用:

string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value)) { /*Operate*/ }

编辑:使代码适应作者的评论:

if (int.TryParse(c, out value) && value >= 1 && value <= 3) { /*Operate*/ }
于 2013-01-13T14:50:44.110 回答
1

int 值 = Convert.ToInt32(c); 如果 c 不是仅由整数组成的字符串,这将失败。使用 try catch 来处理这种情况。

于 2013-01-13T15:06:08.030 回答