2013-03-03 71 views
0

從指定範圍內的用戶獲取有效整數的最佳方式是(0,20),並且是int。如果他們輸入一個無效的整數打印出錯誤。使用while循環和掃描儀驗證輸入

我想是這樣的:

int choice = -1; 
while(!scanner.hasNextInt() || choice < 0 || choice > 20) { 
     System.out.println("Error"); 
     scanner.next(); //clear the buffer 
} 
choice = scanner.nextInt(); 

這是正確的或者是有沒有更好的辦法?

+1

這段代碼,你期待什麼?如果是,那麼你的問題是什麼,如果沒有,那麼錯誤是什麼? – iTech 2013-03-03 06:27:04

+0

即使我鍵入一個數字,它在範圍內,它只是不斷打印出錯 – user1874239 2013-03-03 06:33:45

回答

1

你可以做這樣的事情:

Scanner sc = new Scanner(System.in); 
int number; 
do { 
    System.out.println("Please enter a valid number: "); 
    while (!sc.hasNextInt()) { 
     System.out.println("Error. Please enter a valid number: "); 
     sc.next(); 
    } 
    number = sc.nextInt(); 
} while (!checkChoice(number)); 

private static boolean checkChoice(int choice){ 
    if (choice <MIN || choice > MAX) {  //Where MIN = 0 and MAX = 20 
     System.out.print("Error. "); 
     return false; 
    } 
    return true; 
} 

這一計劃將繼續要求輸入直到它得到一個有效的。

確保你理解程序的每一步..

+0

我剛剛嘗試過這一點,如果選擇不是一個int第一次,它會引發InputMismathException。 – user1874239 2013-03-03 06:48:34

+0

看到我編輯的答案。 – Maroun 2013-03-03 07:05:12

1

你在哪裏更改while循環內的選擇呢?如果它沒有改變,你不能指望在你的if塊的布爾條件中使用它。

您必須檢查掃描儀是否沒有int,如果確實有有一個int,則可以選擇並單獨檢查。

僞代碼:

set choice to -1 
while choice still -1 
    check if scanner has int available 
    if so, get next int from scanner and put into temp value 
    check temp value in bounds 
    if so, set choice else error 
    else error message and get next scanner token and discard 
done while