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

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

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

提交回复
热议问题