2013-10-25 27 views
-1

我有一個有點麻煩,我的代碼:整數掃描儀驗證作用不是應該

int item = -1; 
    Scanner input = new Scanner(System.in); 
    do { 
     while (!input.hasNextInt() || input.nextInt() > 5) { 
      System.out.println("Enter a valid integer!"); 
      getMenu(); 
      input.next(); 
     } 
     item = input.nextInt(); 
    } while (item <= 0); 
    input.close(); 

如果我輸入任何低於5它的工作原理。如果我輸入6,它表明我必須輸入一個有效的整數。當我嘗試再次輸入6時什麼都沒有發生,但是當我再次輸入6時,它會再次向我顯示該消息。我認爲這與input.next()有關,但不太清楚爲什麼。

任何想法?

getMenu()只是顯示一串字符串順便說一句。

換句話說。用戶必須輸入一個介於1和5之間的有效整數。如果用戶不這樣做,他將循環訪問要求輸入有效整數的代碼塊。用戶將循環直到他輸入一個有效的整數。

+1

什麼是'input.next();'應該這樣做?你沒有把它分配給任何東西。 –

+0

我無法得到你想要達到的目標,請分享它,以便我們可以用更好的代碼來幫助你 –

+0

另外,如果'input.nextInt()> 5'結果是錯誤的,那麼你不會存儲或者,'item'最終得到* next *被掃描的整數。 –

回答

1

聲明掃描器內做塊或平齊()值或使用nextLine()來沖洗它

do { 
    Scanner input = new Scanner(System.in); 
    while (!input.hasNextInt() || input.nextInt() > 5) { 
     System.out.println("Enter a valid integer!"); 
     //OR String a = input.nextLine(): 
     getMenu(); 
     input.next(); 
    } 
+0

這工作。我使用'nextLine()' – Ortix92

1

如果您輸入value > 5,您正在閱讀您的while循環中的2個輸入。第一個值由scan.nextInt()本身讀取。然後循環內的scan.next()也讀取一個令牌。

所以,你第一次通過6,while循環條件將被滿足,然後scan.next()將等待輸入。然後,你第二次通過6scan.next()讀取。

而且,你不能從環取出scan.next(),因爲萬一scan.hasNextInt()條件爲false,那麼輸入不會被scan.nextInt()閱讀,然後你的循環會無限的,因爲hasNextInt()將繼續測試相同的輸入。

爲了解決該問題,從while環除去第二條件:

int item = -1; 
Scanner input = new Scanner(System.in); 

do { 
    System.out.println("Enter integer value between [1,5]"); 

    while (!input.hasNextInt()) { // iterate until invalid input is passed 
     System.out.println("Enter a valid integer!"); 
     input.next(); // Read the invalid input to move the cursor ahead 
    } 
    item = input.nextInt(); // Valid input found, read it in `item` 

} while (item <= 0 || item >= 6); 

System.out.println(item); 
input.close();