如何使数字变量不接受文本变量

时间:2015-08-09 09:59:02

标签: c# string visual-studio-2010 if-statement int

back:      Console.Write("The first number=   ");
int x = int.Parse(Console.ReadLine());

if (x== string ) { goto back;} // here my proplem

我如何对此进行建模:如果x输入字符串goto返回

,则表示意思

1 个答案:

答案 0 :(得分:1)

使用循环 int.TryParse ,在正确输入数字时,检查值是否为数字并且中断

    int x;
    while(true)
    {
        Console.Write("The first number=   ");

        bool success = int.TryParse(Console.ReadLine(), out x);

        if (success)
            break;
    }

或者如果您想使用goto

int x;

back:
Console.Write("The first number=   ");

bool success = int.TryParse(Console.ReadLine(), out x);

if (!success)
    goto back;