gpt4 book ai didi

java - try catch 异常无限 while 循环

转载 作者:行者123 更新时间:2023-12-01 17:19:09 27 4
gpt4 key购买 nike

我希望程序在捕获异常时重新执行 while 循环 - 异常正在接收文本输入。相反,它会使用下面的代码继续执行 while 循环,我希望它再次请求用户输入。

import java.util.InputMismatchException;
import java.util.Scanner;

public class NumberGuess {
public static void main(String[] args) {

Scanner Scanner = new Scanner(System.in);

int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;

System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;

// #### Loop here ####
while (inputNum != secretNumber) {
// Try catch
try {

// number too high or too low
if (inputNum > 100 | inputNum < 0) {
System.out.println("Please enter a guess between 0 and " + between + ".");
inputNum = Scanner.nextInt();
}

// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Try higher");
inputNum = Scanner.nextInt();
guesses++;
}

// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Try lower");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
}


System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}

}

输出:

Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher

最佳答案

研究有关扫描仪的文档:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

如果您捕获异常,扫描仪将留在尝试读取号码之前的位置。您必须在 catch block 中使用 nextLine 来推进它。

关于java - try catch 异常无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20032313/

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