C#if语句readline必须等于number

时间:2014-07-22 14:10:06

标签: c# string int

我无法弄清楚要放在括号中的内容,以便我的程序检查输入是否为数字。如果没有,我想返回错误,然后重新启动进程。有什么建议吗?

bool running = true;

Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");

while (running)
{
    victimCount = int.Parse(Console.ReadLine());

    if (/*I want victimCount only to be accepted if it's a number*/)
    {
        Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
    }
    else
    {
        running = false;
    }
}

2 个答案:

答案 0 :(得分:7)

  

我希望victimCount仅在被接受时才被接受

您可以改用int.TryParse方法。它会返回boolean值,表示您的值是有效的int

string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
   // Your value is a valid int.
}
else
{
   // Your value is not a valid int.
}

Int32.TryParse方法默认使用NumberStyles.Integer。这意味着你的字符串可以有;

作为一个号码。

答案 1 :(得分:0)

试试这个:

int victimcount;
bool is Num = int.TryParse(Console.ReadLine(), out victimcount);

If `isNum` is true then the input is an integer. Use this for your check. At the same time, if the parse succeeds, the parsed value gets assigned to the `victimcount` variable (0 is assigned if it fails).