【发布时间】:2021-11-08 04:47:40
【问题描述】:
我正在尝试制作一个程序,用户将在其中输入随机整数/数字。但主要问题是,如果用户不小心输入了一个字符串,我希望他们得到通知,并且我希望他们通过再次询问来再次要求输入。但在我的代码中,我无法循环捕获。
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();
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 if (input == answer ) {
System.out.println("Congrats!");
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println("Guess a Number 1 - 50:");
}
}
}
【问题讨论】:
-
尝试将
nextLine()移动到 catch 中 - 这样,如果当前输入不是有效的 int,您只会快进超过该行。
标签: java