2012-08-23 77 views
3

此代碼檢查用戶是否輸入它是有效的。如果它不是數字,它將繼續循環,直到收到一個數字。之後它將檢查該數字是否在界限內或小於界限。它將繼續循環,直到它收到一個入站號碼。但我的問題是,當我打印選擇時,它只顯示最後插入數字後的前一個數字。爲什麼這樣?使用掃描儀掃描Java輸入

public void askForDifficulty(){ 
    System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: "); 
    int choice = 0; 
    boolean notValid = true; 
    boolean notInbound = true; 
    do{ 
     while(!input.hasNextInt()){ 
      System.out.println("Numbers Only!"); 
      System.out.print("Try again: "); 
      input.nextLine(); 
     } 
      notValid = false; 
      choice = input.nextInt(); 
    }while(notValid); 

    do{ 
     while(input.nextInt() > diff.length){ 
      System.out.println("Out of bounds"); 
      input.nextLine(); 
     } 
     choice = input.nextInt(); 
     notInbound = false; 
    }while(notInbound); 

    System.out.println(choice); 
} 

回答

3

這是因爲input.nextInt()while條件內所消耗的整數,所以它後一個讀取以下之一。 編輯您還需要兩個環相結合,這樣的:

int choice = 0; 
for (;;) { 
    while(!input.hasNextInt()) { 
     System.out.println("Numbers Only!"); 
     System.out.print("Try again: "); 
     input.nextLine(); 
    } 
    choice = input.nextInt(); 
    if (choice <= diff.length) break; 
    System.out.println("Out of bounds"); 
} 
System.out.println(choice); 
+0

我想你的代碼。第二個輸入只有在我輸入數字時才被讀取2次 – KyelJmD

+0

@KyelJmD哦,我看到了 - 你在那裏還有另一個'nextInt',請參閱修正。 – dasblinkenlight

+0

順便說一句你也可以檢查這個問題嗎? http://stackoverflow.com/questions/12082557/java-scanner-validation-returning-the-second-input – KyelJmD