在 Java 中使用 do-while 循环处理异常 [英] Exception handling with a do-while loop in Java

查看:41
本文介绍了在 Java 中使用 do-while 循环处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该算法应该将 3 个整数输入到一个 ArrayList 中.如果输入的不是整数,那么应该会有提示.当我执行我的代码时,catch 子句被执行,但程序运行到一个无限循环中.有人可以引导我走向正确的方向,我很感激帮助.:-D

The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is executed, but the program runs into a infinite loop. Could someone guide me into the right direction, I appreciate the help. :-D

package chapter_08;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class IntegerList {
    static List<Integer> numbers = new ArrayList<Integer>();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 1;
        int inputNum;

        do {
            System.out.print("Type " + counter + " integer: " );
            try {
                inputNum = input.nextInt();
                numbers.add(inputNum);
                counter += 1;
            }
            catch (Exception exc) {
                System.out.println("invalid number");
            }
        } while (!(numbers.size() == 3));
    }
}

推荐答案

那是因为当使用 nextInt() 读取下一个 int 并且失败时,Scanner仍然包含键入的内容.然后,当重新进入 do-while 循环时,input.nextInt() 尝试使用相同的内容再次解析它.

That is because when the next int is read using nextInt() and it fails, the Scanner still contains the typed contents. Then, when re-entering the do-while loop, input.nextInt() tries to parse it again with the same contents.

您需要使用 nextLine() 来刷新"Scanner 的内容:

You need to 'flush' the Scanner contents with nextLine():

catch (Exception exc) {
    input.nextLine();
    System.out.println("invalid number");
}

<小时>

注意事项:

  • 您可以删除 counter 变量,因为您没有使用它.否则,您可以将 counter += 1 替换为 counter++.
  • 您可以将 while (!(numbers.size() == 3)) 替换为 while (numbers.size() != 3),甚至更好: while (numbers.size() <3).
  • 在捕获异常时,您应该尽可能具体,除非您有充分的理由不这样做.在您的情况下,Exception 应替换为 InputMismatchException.
  • You can remove the counter variable, because you're not using it. Otherwise, you could replace counter += 1 by counter++.
  • You can replace while (!(numbers.size() == 3)) with while (numbers.size() != 3), or even better: while (numbers.size() < 3).
  • When catching exceptions, you should be as specific as possible, unless you have a very good reason to do otherwise. Exception should be replaced by InputMismatchException in your case.

这篇关于在 Java 中使用 do-while 循环处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆