// Precondition: number provided is a positive integer
// Postcondition: returns a integer of length 4
public static int validateNumber(int num, Scanner scan)
{
int number = num;
while(number < 1000 || number > 9999)
{
try
{
System.out.print("Number must be 4 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
scan.nextLine();
}
catch(InputMismatchException e) //outputs error message if value provided is not an integer
{
System.out.println("Incorrect input type.");
}
}
return number;
}
假设前提条件得到满足,当这种方法被执行,然后输入一个字符串来测试程序后,我得到一个无限循环。 为什么这个问题发生,我将如何解决?