C#如何循环用户输入,直到输入的数据类型正确? [英] C# How to loop user input until the datatype of the input is correct?

查看:33
本文介绍了C#如何循环用户输入,直到输入的数据类型正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to make this piece of code loop asking for input from the user until 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'
    }

有用答案后的代码版本:

Version of the code after the helpful answer:

 //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;
        }
    }

推荐答案

while (!int.TryParse(Console.ReadLine(), out mynum))
    Console.WriteLine("Try again");

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: ");
}

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

Try this. I personally prefer to use while, but do .. while is also valid solution. The thing is that I don't really want to print error message before any input. However while has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to use goto even tho some people would probably track me down and slap me with a fish because of it.

这篇关于C#如何循环用户输入,直到输入的数据类型正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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