C#如何循环用户输入,直到输入的数据类型正确?

Blo*_*ine 0 c# console loops input

如何使这段代码循环请求用户输入直到int.TryParse()

成功了吗?

//setX
    public void setX()
    {
        //take the input from the user
        string temp;
        int temp2;
        System.Console.WriteLine("Enter a value for X:");
        temp = System.Console.ReadLine();
        if (int.TryParse(temp, out temp2))
            x = temp2;
        else
            System.Console.WriteLine("You must enter an integer type value"); 'need to make it ask user for another input if first one was of invalid type'
    }
Run Code Online (Sandbox Code Playgroud)

有用答案之后的代码版本:

 //setX
    public void setX()
    {
        //take the input from the user
        string temp;
        int temp2;
        System.Console.WriteLine("Enter a value for X:");
        temp = System.Console.ReadLine();
        if (int.TryParse(temp, out temp2))
            x = temp2;
        else
        {
            Console.WriteLine("The value must be of integer type");
            while (!int.TryParse(Console.ReadLine(), out temp2))
                Console.WriteLine("The value must be of integer type");
            x = temp2;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Luk*_*tný 7

while (!int.TryParse(Console.ReadLine(), out mynum))
    Console.WriteLine("Try again");
Run Code Online (Sandbox Code Playgroud)

编辑:

public void setX() {
    Console.Write("Enter a value for X (int): ");
    while (!int.TryParse(Console.ReadLine(), out x))
        Console.Write("The value must be of integer type, try again: ");
}
Run Code Online (Sandbox Code Playgroud)

试试这个.我个人更喜欢使用while,但do .. while也是有效的解决方案.问题是我不想任何输入之前打印错误消息.然而while,对于不能被推入一行的更复杂的输入也存在问题.这真的取决于你究竟需要什么.在某些情况下,我甚至建议使用goto甚至一些人可能会跟踪我并因为它而用鱼打我.