How to restrict the user input to five digits?

后端 未结 6 1258
生来不讨喜
生来不讨喜 2021-01-26 11:11

I\'m trying to restrict the user to only input 5 digits into the console for C#. I have my code error check the user, but for some reason after I type let\'s say...6 digits, the

6条回答
  •  -上瘾入骨i
    2021-01-26 11:34

    dont use Console.Readline() again and again

    change your code like this.

        Console.WriteLine("Enter the the zip code of the contact.");
         var temp = int.Parse(Console.ReadLine());
    
            while (temp.ToString().Length != 5)
            {
                Console.WriteLine("Error. Zip code is not 5 digits. Please enter a valid number.");
                temp = int.Parse(Console.ReadLine());
    
                if (temp.ToString().Length == 5)
                {
                    temp = int.Parse(Console.ReadLine());
    
                }
            }
    

    (to save from null reference you can do if(temp < 100000 && temp > 9999) also.)

提交回复
热议问题