为什么Java中while循环无法像if else语句那样让catch块循环执行?
问题原因
- 当
Scanner调用nextInt()触发InputMismatchException时,不会消费掉输入缓冲区中不匹配的字符串内容,下次循环再次调用nextInt()时会重复读取同一个错误输入,导致无限触发异常。 - 原有代码猜对数字后没有终止循环,程序会一直处于运行状态。
- 原有代码没有做1-50的输入范围校验,不符合需求要求。
修复方案
在catch块中添加scan.nextLine()清空缓冲区的错误输入,同时在猜对数字的分支添加break退出循环,额外补充输入范围校验逻辑。
修正后完整代码
import java.util.InputMismatchException; import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int answer = 28; int attempts = 0; System.out.println("Guess a Number 1 - 50:"); while(true) { try { int input = scan.nextInt(); scan.nextLine(); attempts++; // 补充输入范围校验 if(input > 50 || input < 1) { System.out.println("Please enter a number between 1 and 50:"); continue; } if(input > answer) { System.out.println("Too Big"); System.out.println("Guess a Number 1 - 50:"); } else if (input < answer) { System.out.println("Too Small"); System.out.println("Guess a Number 1 - 50:"); } else { System.out.printf("Congrats! You got it in %d attempts.%n", attempts); break; // 猜对后退出循环 } } catch (InputMismatchException e) { scan.nextLine(); // 清空缓冲区错误输入,解决死循环问题 System.out.println("Numbers only"); System.out.println("Guess a Number 1 - 50:"); } } scan.close(); } }
内容的提问来源于stack exchange,提问作者Pablo Job
相关产品推荐
相关产品推荐

