有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的异常处理会导致无限循环?

我正在编写一个返回整数值的方法。在该方法中,我通过scanner类通过控制台提示用户输入整数

因为我使用的是scanner方法“scan.nextInt()”,所以我还要检查“InputMismatchException”错误。我已经将异常处理放在一个循环中,这样,如果捕获到异常,就会通知用户并重复该循环。这将要求用户不断输入值,直到只输入整数值

但是,我的问题是,在它第一次检查错误之后,当它返回时,发生了一些事情,没有提示用户输入新值,并且再次抛出异常。这当然会导致无限循环

我已经研究并发现了一些与该问题相关的案例,我也尝试过执行相关的修复,但我所做的一切似乎都不起作用,我不知道到底发生了什么。正在跳过try块吗?我的try块的符号有问题吗

public static int inputCheck() {
int check=0;
int money = 0;
while (check==0) {
  boolean error = false;
  System.out.println("Please enter the amount of money your player has.");
  while (true) {
    try {
      money = scan.nextInt();
    }catch (InputMismatchException wrongInput) {
      System.out.println("Error. Please enter an integer value." + wrongInput);
      error = true;
    }
    break;
  }
  if (error==false)
    check++;
  }
return money;
}

编辑代码已被编辑,“错误”布尔值已被调整


共 (3) 个答案

  1. # 1 楼答案

    当您将error设置为true时,问题在于捕获。一旦error设置为true,您的循环将以一种无法退出的方式构造,因为error永远不会设置为false,因此check永远不会递增。一般来说,我会重新构造这个循环系统,有更好的方法来处理这个问题

  2. # 2 楼答案

    while(true)从不为false,因此如果循环未命中break语句,则循环永远不会终止

  3. # 3 楼答案

    试试这个:

    public static int inputCheck() {
        int check = 0;
        int money = 0;
    
        while (check == 0) {
            boolean error = false;
            System.out.println("Please enter the amount of money your player has.");
            try {
                money = Integer.parseInt(scan.next());
            } catch (Exception e) {
                System.out.println("Error. Please enter an integer value." + e);
                error = true;
            }
            if (error == false) {
                check++;
            }
        }
        return money;
    }