我正在制作一個小型文字游戲,它要求用戶從選項 1 到 3 中進行選擇,1 和 2 是游戲,3 是退出。我為正確的整數設定了錯誤處理,但不確定為什么當用戶輸入不是整數的內容時程式會崩潰。
匯入 java.util.Scanner;
公共類 Small_Programming_Assignment {
public static void main(String[] args) {
getSelection();
substringProblem();
pointsProblem();
}
public static void getSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("");
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
int choice = sc.nextInt();
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else if (!sc.hasNextInt() ) {
System.out.println("Invalid option. Try again.");
getSelection();
} else {
System.out.println("Invalid option. Try again.");
getSelection();
}
}
public static void substringProblem() {
System.out.println("Substring Problem");
getSelection();
}
public static void pointsProblem() {
System.out.println("Points Problem");
getSelection();
}
}
我正在嘗試使用 (!sc.hasNextInt() ) 但似乎程式在達到此之前崩潰了。
uj5u.com熱心網友回復:
據我所知,每當我輸入一個不是整數的值時,程式都會拋出一個名為InputMismatchException.
根據Oracle 的 Java 檔案:
由 Scanner 拋出以指示檢索到的令牌與預期型別的??模式不匹配,或者令牌超出預期型別的??范圍。
該程式沒有到達您的“無效選項。再試一次。” 陳述句,因為在用戶輸入后直接拋出例外,這意味著您不能通過Scanner'nextInt()方法提供除整數以外的任何內容。
如果您仍想使用此方法,您可以做的是將它放在一個try/catch陳述句中,如下所示:
int choice = 0;
try {
choice = sc.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Invalid option. Try again.");
getSelection();
}
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid option. Try again.");
getSelection();
}
這應該可以完成這項作業。現在,每當用戶鍵入無法決議為 Integer 的內容時,就會拋出運行時例外并被捕獲,因此程式進入該catch塊,輸出“Invalid option. Try again”。和“重新”呼叫getSelection()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529465.html
下一篇:檢查條件Python
