[英]Scanner outside Java while loop
我正在創建一種方法,讓用戶通過與數字相關的 2 個選擇來選擇他想做的事情。 如果用戶在輸入中插入任何字符串,我的代碼將無限打印:
Choose an optionError
1 - New game
2 - Load game
在所有其他情況下代碼工作正常,所以我認為錯誤在 catch() 中。 我嘗試使用代碼某些部分中的說明關閉掃描儀 object,但問題仍然存在。
相反,如果我在 Start() 方法的 while 循環內聲明 Scanner object,代碼將完美運行。 我不知道掃描儀 object 是如何工作的,也不知道為什么會出現這個問題。
import java.util.Scanner;
public class Metods {
static Scanner input = new Scanner(System.in);
public static int Start() {
while(true) {
int choice;
System.out.println("1 - New game");
System.out.println("2 - Load game");
System.out.print("\nChoose an option");
try {
choice = input.nextInt();
//input.close();
} catch (Exception e) {
System.out.println("Error");
//input.close();
continue;
}
if (choice == 1 || choice == 2) {
//input.close();
return choice;
}
else {
System.out.println("Error");
//input.close();
}
}
}
}```
在每個循環中,您都試圖再次解析輸入。 nextInt() 方法拋出異常,但輸入仍未處理,因此下一個循環再次嘗試解析輸入...
您應該將輸入讀取為字符串,檢查它是否是有效選項(1 或 2)並將選項作為 integer 返回(如果需要),否則循環將再次開始等待新輸入,因為您的輸入已處理。
我只是更改了相關部分。
public static int start() {
while(true) {
String choice;
System.out.println("1 - New game");
System.out.println("2 - Load game");
System.out.print("\nChoose an option");
try {
choice = input.next();
//input.close();
} catch (Exception e) {
System.out.println("Error");
//input.close();
continue;
}
if (choice.equals("1") || choice.equals("2")){
//input.close();
return Integer.parseInt(choice);
}
else {
System.out.println("Error");
//input.close();
}
}
}
因為nextInt讀到的數據不是一個integer,但是並沒有自動跳過數據。
您可以使用 input.next() 方法跳過錯誤的字符
static Scanner input = new Scanner(System.in);
public static int Start() {
while(true) {
int choice;
System.out.println("1 - New game");
System.out.println("2 - Load game");
System.out.print("\nChoose an option");
try {
choice = input.nextInt();
//input.close();
} catch (Exception e) {
System.out.println("Error");
if( input.hasNext() ) {
input.next();
}
//input.close();
continue;
}
if (choice == 1 || choice == 2) {
//input.close();
return choice;
}
else {
System.out.println("Error");
//input.close();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.