2016-04-26 77 views
0

我希望用戶輸入80到120之間的整數,沒有字母和其他符號。這裏是我的代碼:如何檢查用戶是否輸入2個數字之間的整數?

import java.util.*; 

public class Test {  

public static void main(String[] args) 
{  
    Scanner in = new Scanner(System.in); 

//checking for integer input 
    while (!in.hasNextInt()) 
    { 
     System.out.println("Please enter integers between 80 and 120."); 
     in.nextInt(); 
     int userInput = in.nextInt(); 

//checking if it's within desired range 
     while (userInput<80 || userInput>120) 
     { 
      System.out.println("Please enter integers between 80 and 120."); 
      in.nextInt(); 
     } 
    } 
} 

}

不過,我面臨的一個錯誤。有針對這個的解決方法嗎?

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at Array.main(Array.java:15) 

謝謝! :)

編輯:謝謝湯姆,得到了解決,但想嘗試沒有「做」

Scanner in = new Scanner(System.in); 

    int userInput; 
    do { 
    System.out.println("Please enter integers between 80 and 120."); 
    while (!in.hasNextInt()) 
    { 
     System.out.println("That's not an integer!"); 
     in.next(); 
     } 
     userInput = in.nextInt(); 
} while (userInput<81 || userInput >121); 

System.out.println("Thank you, you have entered: " + userInput); 
} 
} 
+0

當然有!抓住java.util.InputMismatchException並適當處理它。出於興趣,你爲什麼要跳過輸入? – Bathsheba

+0

@Bathsheba你好,我想這樣做沒有使用捕捉,因爲我正在修改我的學校工作,這只是前幾個主題(在這一點上沒有學到異常) – Ken

+0

將條件改爲while (in.hasNextInt()) – Unknown

回答

0

你的循環條件是錯誤的。你可以檢查「只要輸入中沒有可用整數:讀取一個整數」。這是失敗

另外:你打電話nextInt兩次。不要這樣做。刪除第一個電話:

System.out.println("Please enter integers between 80 and 120."); 
in.nextInt(); //REMOVE THIS LINE 
int userInput = in.nextInt(); 

如果int可以使用hasNextInt要檢查一次,但你讀值的兩倍!

+0

我試過了,仍然收到相同的錯誤。 – Ken

+0

是的,我嘗試刪除它,我仍然有同樣的錯誤D: – Ken

+1

'while(!in.hasNextInt())'也許你的問題在這裏。 –

0
boolean continueOuter = true; 

    while (continueOuter) 
     { 
      System.out.println("Please enter integers between 80 and 120."); 
      String InputVal = in.next(); 

     try { 
      int input = Integer.parseInt(InputVal); 
       //checking if it's within desired range 
      if(FirstInput>80 && FirstInput<120) 
      { 
       //no need to continue got the output 
       continueOuter = false; 
      }else{ 
        System.out.println("Please enter integers between 80 and 120."); //need to continue didnt got the exact output 
       continueOuter = true;  
      } 

     } catch (Exception e) { 
     //not an int  
     System.out.println(InputVal); 
     continueOuter = true; 
     } 
} 

在這段代碼中,我已經創建了一個布爾值來檢查程序是否想繼續執行。如果用戶輸入了有效值,程序將停止 ,但是您可以根據需要更改該值。你不需要兩個while循環我已經改變了內部while循環到if循環看看我的代碼

+1

'continue = false'?在Java中祝好運。 – Bathsheba

+0

我指的是continueouter,這是一個錯誤。 – Priyamal

+0

@priyamal你好,如果用戶輸入一個字符呢?我頭人物是指數字或其他東西。 – Ken

相關問題