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

C# How to loop user input until the datatype of the input is correct?(C#如何循环用户输入,直到输入的数据类型正确?)
本文介绍了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#如何循环用户输入,直到输入的数据类型正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)