【问题标题】:Try-Catch inside While Loop在 While 循环中进行 Try-Catch
【发布时间】:2014-09-11 11:37:45
【问题描述】:

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

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(); 发生了什么,为什么用户无法输入数字?

【问题讨论】:

  • 基本上,您会一次又一次地遇到异常。这大概是因为错误的输入仍然在那里等待读取。

标签: java exception-handling while-loop try-catch inputmismatchexception


【解决方案1】:

为什么要使用带有 try 和 catch 的循环?

我的建议是始终使用带有 while 或 do while 循环的 try 和 catch,这样您就可以要求用户重复他/她的输入。它还取决于您已经使用的循环和/或代码的结构。

例如,如果您已经有一个 do while 循环,那么我建议您简单地调整/修改您现有的循环。

我将发布一些示例,说明如何在用户提供错误输入后使用循环来重复输入。

见下面的例子:

示例 1

Scanner input = new Scanner(System.in);
int exampleInput = 0;
do {
    try {
        System.out.print("\nEnter an integer from 1 to 25: ");
        exampleInput = input.nextInt();
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer from 1 to 25");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (exampleInput < 1 || exampleInput > 25);
System.out.println("Print exampleInput: " + exampleInput);

示例 2

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDone = false;
do {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDone = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (!isDone);
System.out.println("Print exampleInput: " + exampleInput);

示例 3

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDoneLoop2 = false;
while (!isDoneLoop2) {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDoneLoop2 = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
}
System.out.println("Print exampleInput: " + exampleInput);

【讨论】:

    【解决方案2】:

    今天我解决了这个问题 :-) 这是我的代码。我认为我有帮助

    public int choice () throws Exception{
        Scanner read = new Scanner(System.in));
        System.out.println("Choose the option from the upper list");
        int auxiliaryChoiceMenu = 5;
        int auxiliaryVariable = -1;
        boolean auxiliaryBoolean = false;
        while (!auxiliaryBoolean) {
            try {
                auxiliaryVariable = read.nextInt();
                read.nextLine();
            } catch (Exception e) {
                System.out.println("incorrect data, try again"+e);
                read.nextLine();
                continue;
            }
    
            if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
                System.out.println("incorrect data, try again");
            } else {
                auxiliaryBoolean = true;
            }
            choiceMenu = auxiliaryVariable;
    
        }
            return choiceMenu;
            //choicemenu is a external variable
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我知道是因为时间限制。
      • 为什么需要continue?这只是 java 的一个怪癖吗?
      • @ycomp continue 在这种情况下不需要。
      【解决方案4】:

      您可能需要创建一个 Scanner 类来获取从键盘流式传输的标准输入。您应该在代码中的某处创建一个 Scanner 类的实例,例如:Scanner in = new Scanner(System.in); 所以你声明中的“ in ”变量:amountRacers = in.nextInt();等待并扫描从键盘输入的输入并将其存储。

      【讨论】:

      • 这只是一段代码,我已经实例化了 Scanner 对象。
      猜你喜欢
      • 2015-04-24
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多