2014-05-15 63 views
0

我打印不同的選項,用戶輸入一個數字來選擇正確的選項。它第一次工作,但是當選擇了一個選項時,它會根據選定的選項打印不同的選項。當用戶試圖從第二個打印列表中選擇一個選項時,程序會陷入無限循環。無限循環使用Scanner.hasNextInt

protected int getIntegerInput(Scanner scan) { 
    while (! scan.hasNextInt()) 
     ; 
    return scan.nextInt(); 
} 

protected <T> int getChoice(String description, List<T> list) { 
    printPosibilities(description, list); 
    while (true) { 
     try (Scanner scan = new Scanner(System.in)) { 
      int choice = getIntegerInput(scan) - 1; 
      scan.close(); 
      if (isValidChoice(choice, list)) { 
       if (choice == list.size()) { 
        System.out.println("Canceled."); 
        return CANCEL; 
       } 
       return choice; 
      } else 
       throw new IllegalArgumentException(); 
     } catch (InputMismatchException | IllegalArgumentException e) { 
      printInvalidChoice(); 
     } 
    } 
} 

它在getIntegerInput()中被卡住了。當打印可能的選項時調用getChoice()。

編輯 我固定它。您需要刪除該試卷,因爲它會自動關閉掃描器。 while循環中的scan.next()。

回答

5

您需要從Scanner

while (!scan.hasNextInt()) { 
    scan.next(); // consume non-integer values 
} 
+0

這導致 'NoSuchelementException' 第一個列表是相同的,但是當第二個列表打印時,這會導致錯誤。 – SBylemans

+0

但每次打印新選項列表時都會啓動掃描儀。這並不重要。 – SBylemans

+0

但是每個掃描器都使用相同的'System.in',所以第一次它關閉的後續'Scanner'實例不能從'InputStream'中讀取 – Reimeus

0

簡短的解釋消耗輸入高於,但這裏更多的掃描儀一點:

Scanner這樣的思考。

假設你給了String,「Hello world,this is a String!」
想象它被每個空白空間分解''。

每次在掃描儀上調用.next()時,它都會將緩衝區移動到下一個空白處。

所以...這個例子:

Scanner.next() 
// grabs Hello 
// "Hello world, this is a String!" 
//  ^Buffer 
Scanner.next() 
// grabs world, 
// "Hello world, this is a String!" 
//   ^Buffer` 

在你的情況下,由於您使用的是while()循環,你需要調用.next()(或.nextInt())循環內的某處。

避免在條件語句和返回語句中放入.next()調用。我不確定具體情況,但它通常會在不出錯的情況下破壞你的信息。