我对代码中的 catch 语句之后的操作有点困惑。异常被抛出并在循环中捕获后,循环变为无限。我还发现输入一个很长的数字序列(+10 左右)会导致循环无限。我对java中的异常处理相当陌生,所以详细的描述会很有教育意义。
public static void main(String[] args)
{
boolean cont = false;
while (!cont)
{
addInputNumber();
cont = tryAgain();
}
}
private static void addInputNumber ()
{
boolean valid;
int total;
int inputInt;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.print("Enter a number(between 0 and 1000)");
inputInt = input.nextInt();
if(inputInt > 0 && inputInt < 1000)
{
valid = true;
total = (inputInt % 10) + ((inputInt / 10) % 10) + (inputInt / 100);
System.out.println("\n" + "The total of " + inputInt + " is " + total);
}
else
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
}
catch(InputMismatchException ex)
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
} while(!valid);
}