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

前端 未结 4 1529
春和景丽
春和景丽 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: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.

提交回复
热议问题