2012-07-24 91 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); 
     } 
    } 
}