2012-10-25 62 views
3

嘗試將用戶輸入作爲0到100之間的整數,並且只要輸入與此條件不匹配,就提示用戶「再試一次」。如何提示用戶輸入0到100之間的數字?

我的代碼迄今爲實現我的目標有些成功:

import java.util.Scanner; 

public class FinalTestGrade 
{ 
    public static void main(String[] args) 
    { 
     Scanner studentInput = new Scanner (System.in); 
     int testGrade; 

     System.out.println("Please enter your test grade (0 to 100)"); 
     while (!studentInput.hasNextInt()) 
      { 
      System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 
      studentInput.next(); 
      } 
     testGrade = studentInput.nextInt(); 

     while (testGrade > 100 || testGrade < 0) 
      { 
      System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 
      testGrade = studentInput.nextInt(); 
      } 

正如你所看到的,該程序將檢查輸入的是一個int。一旦用戶成功輸入一個int,程序將檢查以確保它們的輸入介於0和100之間。當第二個提示符響應 (由第二個while循環啓動)時,用戶輸入一個非int值時出現問題。下面是一個例子:

run: 
Please enter your test grade (0 to 100) 
P 
Your input does not match the criteria, please enter a number between 0 and 100 
109 
Your input does not match the criteria, please enter a number between 0 and 100 
P 
    Exception in thread "main" java.util.InputMismatchException 
      at java.util.Scanner.throwFor(Scanner.java:840) 
      at java.util.Scanner.next(Scanner.java:1461) 
      at java.util.Scanner.nextInt(Scanner.java:2091) 
      at java.util.Scanner.nextInt(Scanner.java:2050) 
      at finaltestgrade.FinalTestGrade.main(FinalTestGrade.java:24) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 9 seconds) 

所以長話短說,我不知道是否有一種方法我同時結合循環,使輸入表示爲0和100之間的一個int被接受&保存爲一個變量。所有不符合此標準的輸入應該會觸發一個重複的提示,直到輸入滿足該條件。有什麼建議麼?

回答

0
int testGrade = -1 ; 
Scanner studentInput = new Scanner(System.in); 
while (testGrade > 100 || testGrade < 0) 
{ 
    System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 

    while(!studentInput.hasNextInt()) 
    { 
     studentInput.next() ; 
    } 
    testGrade = studentInput.nextInt(); 
} 

有一個無限循環來檢查流中是否有無效字符。如果是這樣,消耗它,那是什麼hasNextInt()是。如果您輸入了有效的內容,則會退出該循環。

+0

這是一個非常優雅的解決方案,但是當我運行它時,我得到一個無限循環: 您的輸入與條件不符,請輸入0到100之間的數字 輸入的輸入無效! 您的輸入與標準不符,請輸入0到100之間的數字 輸入的輸入無效! 等等等等有什麼建議? –

+0

mmn讓我試試 –

+0

@ user1775753修改。讓我知道事情的後續。 –

相關問題