gpt4 book ai didi

java - 在 While 循环中 try catch

转载 作者:行者123 更新时间:2023-12-04 22:55:51 26 4
gpt4 key购买 nike

下面的代码询问用户他/她想要多少赛车手。

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
}
}

如果在 amoutnRacers = in.nextInt(); 处输入一个数字,则代码跳出循环,程序的其余部分运行良好;但是,当我输入诸如“awredsf”之类的内容时,它应该捕获该异常,它确实做到了。它不是再次提示用户,而是连续循环,这对我来说没有意义。

程序在连续循环时打印如下:

应该有多少赛车手参加比赛?
应该有多少赛车手参加比赛?
应该有多少赛车手参加比赛?
应该有多少赛车手参加比赛?
应该有多少赛车手参加比赛?
应该有多少赛车手参加比赛?
应有多少车手参加比赛?请输入数字!空值
请输入数字!空值
请输入数字!空值
请输入数字!空值
请输入数字!空值
请输入数字!空值
请输入数字!空值
...

我不明白 amountRacers = in.nextInt(); 发生了什么,为什么用户无法输入数字?

最佳答案

捕获 InputMismatchException 后只需添加 input.next()

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
}

您需要清除错误的输入,而扫描仪自动不会这样做。

关于java - 在 While 循环中 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com