How to restrict the user input to five digits?

后端 未结 6 1265
生来不讨喜
生来不讨喜 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:36

    Please view the code given below. I think this will fulfill your requirement. I have found that you have use address.zipCode which has not been declared anywhere in given code so I have replace the address.zipCode with zipCode.

            int temp,zipCode;
    
            bool breakLoop = false;
    
            Console.WriteLine("Enter the the zip code of the contact.");
    
            while (breakLoop == false)
            {
                string userInput = Console.ReadLine();
                if (userInput.Length != 5)
                {
                    Console.WriteLine("Error. Zip code is not 5 digits. Please enter a valid number.");
                    continue;
                }
    
                int.TryParse(userInput, out temp);
                if (temp == 0)
                {
                    Console.WriteLine("Error. Please enter a valid number.");
                    continue;
                }                
    
                zipCode = temp;
                breakLoop = true;
                break;
    
            }
    

    Please let me know if you have any problem with the code.

提交回复
热议问题