Java输入缓冲垃圾

时间:2012-07-24 16:46:20

标签: java

为什么在这样的代码块中从输入缓冲区清空'Garbage'是好的做法?如果我没有会发生什么?

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();
}

1 个答案:

答案 0 :(得分: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);
        }
    }
}