C# How to loop user input until the datatype of the input is correct?

前端 未结 4 1528
春和景丽
春和景丽 2020-12-03 16:34

How to make this piece of code loop asking for input from the user until int.TryParse()

is successful?

//setX
    public void setX()
    {
          


        
相关标签:
4条回答
  • 2020-12-03 17:04
    while (!int.TryParse(Console.ReadLine(), out mynum))
        Console.WriteLine("Try again");
    

    edit:

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

    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.

    0 讨论(0)
  • 2020-12-03 17:04

    Even though the question has been already marked as answered, do-while loops are much better for validating user input.

    Notice your code:

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

    You have the same code at top and bottom. This can be changed:

    do {
        Console.WriteLine("The value must be of integer type");
    } while (!int.TryParse(Console.ReadLine(), out temp2));
    
    0 讨论(0)
  • 2020-12-03 17:15

    This can help too

    public int fun()
    {
        int Choice=0;
        try 
        {
            Choice = int.Parse(Console.ReadLine());
            return choice;
        } 
        catch (Exception) 
        {
            return fun(); 
        }
    }
    
    0 讨论(0)
  • 2020-12-03 17:23

    I've been wondering quite a lot, but I just figured it out!

        int number;
        bool check;
        do
        {
            Console.WriteLine("Enter an integer:");
            check = int.TryParse(Console.ReadLine(), out num1);
        }
        while (!check);
    

    This code will loop until the user has entered an integer number. This way, the program doesn't simply report an error, but instead immediately allows the user to input again another, correct value.

    0 讨论(0)
提交回复
热议问题