2012-07-24 97 views
-1

为什么最好的做法是在这样的代码块中清空输入缓冲区中的“垃圾”?如果我没有,会发生什么?Java输入缓冲区垃圾

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

回答

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