Rhe*_*ndz 0 java exception-handling try-catch while-loop inputmismatchexception
下面的代码询问用户他/她想要多少赛车手.
while (true) { // loops forever until break
try { // checks code for exceptions
System.out.println("How many racers should" + " participate in the race?");
amountRacers = in.nextInt();
break; // if no exceptions breaks out of loop
}
catch (InputMismatchException e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
continue; // continues to loop if exception is found
}
}
Run Code Online (Sandbox Code Playgroud)
如果在amoutnRacers = in.nextInt();
代码中输入一个数字,则循环出来并且程序的其余部分运行正常; 但是,当我输入诸如"awredsf"之类的内容时,它应该捕获该异常,它会这样做.而不是再次提示用户它不断循环,这对我来说没有意义.
程序在连续循环时打印如下:
有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少赛车手参加比赛?请输入一个号码!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!空值 ...
我不明白发生了什么amountRacers = in.nextInt();
,为什么用户无法输入号码?
input.next()
一旦捕获InputMismatchException,只需添加 .
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
input.next(); // clear scanner wrong input
continue; // continues to loop if exception is found
}
Run Code Online (Sandbox Code Playgroud)
您需要清除错误的输入,而扫描仪自动不会.