-1

为什么在这样的代码块中清空输入缓冲区中的“垃圾”是一种好的做法?如果我不这样做会怎样?

try{
    age = scanner.nextInt();
    // If the exception is thrown, the following line will be skipped over.
    // The flow of execution goes directly to the catch statement (Hence, Exception is caught)
    finish = true;
} catch(InputMismatchException e) {
    System.out.println("Invalid input. age must be a number.");
    // The following line empties the "garbage" left in the input buffer
    scanner.next();
}
4

1 回答 1

2

假设您正在循环读取扫描仪,如果您不跳过无效令牌,您将永远继续阅读它。就是这样scanner.next()做的:它将扫描仪移动到下一个令牌。请参阅下面的简单示例,该示例输出:

发现 int: 123
输入无效。年龄必须是一个数字。
跳过:abc
找到 int:456

如果没有该String s = scanner.next()行,它将继续打印“无效输入”(您可以尝试注释掉最后两行)。


public static void main(String[] args) {
    Scanner scanner = new Scanner("123 abc 456");
    while (scanner.hasNext()) {
        try {
            int age = scanner.nextInt();
            System.out.println("Found int: " + age);
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. age must be a number.");
            String s = scanner.next();
            System.out.println("Skipping: " + s);
        }
    }
}
于 2012-07-24T16:53:04.907 回答