我得到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();
}
如果只是有辦法去嘗試的東西,然後捕捉異常做在這些情況下的東西......就像描述這裏]什麼是(https://docs.oracle.com/javase/tutorial/essential/例外/) – csmckelvey
我試圖用一個try-catch塊,但它仍顯示而不是打印的「不正確」的消息 – Navi4458
這不是try/catch塊的錯錯誤 - 問題是你如何編碼它。如果您向我們展示該代碼,我們可能可以解釋爲什麼是這種情況。 – csmckelvey