2017-04-14 49 views
0

我得到java.util.InputMismatchException每次輸入字母時。我希望它顯示「不正確的消息」而不是崩潰。我試着讓x字符串和解析輸入,但問題仍然是一樣的。不太確定如何做到這一點。這裏是我的代碼:java.util.InputMismatchException在我的整數驗證方法

public static void generateDivision() { 

    Random rand4 = new Random(); 
    Scanner keyboard6 = new Scanner(System.in); 

    int random = rand4.nextInt(12); 
    int random2 = rand4.nextInt(12); 

    //Following two lines ensures that no remainders are present so the numbers divide evenly. 
    int n = random * random2;    
    int k = n/random;     

    System.out.println(n + "/" + random + " = ?"); 
    int x = keyboard6.nextInt(); 

    checkUserAnswer(k, x); 
} 
public static void checkUserAnswer(int n, int x) { 

    try { 
     if (n == x) { 

      System.out.println("Correct!"); 
      System.out.println(); 


     } 
     if (n != x) { 

      System.out.println("Incorrect!"); 
      System.out.println(); 


     } 
    } catch (InputMismatchException e) { 
     System.out.println("Incorrect! That was not a number."); 

    } 
    updateStats(n, x); 
    tryAgain(); 

    } 
+0

如果只是有辦法去嘗試的東西,然後捕捉異常做在這些情況下的東西......就像描述這裏]什麼是(https://docs.oracle.com/javase/tutorial/essential/例外/) – csmckelvey

+0

我試圖用一個try-catch塊,但它仍顯示而不是打印的「不正確」的消息 – Navi4458

+0

這不是try/catch塊的錯錯誤 - 問題是你如何編碼它。如果您向我們展示該代碼,我們可能可以解釋爲什麼是這種情況。 – csmckelvey

回答

0

你應該在你的代碼中使用try/catch塊,例如:

try 
{ 
    //Code to do 
}catch(InputMismatchException ex) 
{ 
    System.out.print("Sorry, try entering another value"); 
} 

你把你所有的輸入代碼try塊,如果失敗,你趕上它與catch塊給它一個你想在這種情況下它是InputMismatchException異常。希望這有助於:)

+0

我只是試着這樣做。當我測試它。該錯誤仍然彈出,我的消息不顯示。 – Navi4458

+0

您可以發佈您使用try catch塊的代碼嗎? – Aaron

+0

我剛剛更新了我剛剛嘗試過的問題。 – Navi4458

0

函數nextInt()總是期望輸入爲int,並且如果用戶輸入的內容不是int,則會拋出異常。

您可以使用try-catch語法來捕獲InputMismatchException,而不是拋出異常,向用戶傳遞消息。或者,你可以採取用戶輸入作爲String(也許nextLine()),並解析int /自己給相應的錯誤消息。然而,有沒有意義的重新發明輪子,所以使用nextInt()的內置解析和try-catch是清潔的選擇。

如果你想要一個介紹與try-catch處理異常,the Java doc可能會有所幫助。