我正在做一项学校作业,这一次我考虑使用 switch 语句,因为它看起来更有效。
这只是一些基本的东西,但如果我输入一个字母,例如在数字 1 之后,它会返回 case 1 两次?
这是我迄今为止整个类(class)的代码:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
private int option;
public static void main(String[] args) {
Test t = new Test();
t.start();
t.optionMenu();
}
public void start() {
System.out.println("Make your choice:");
System.out.println("1: Play");
System.out.println("2: Options");
System.out.println("3: Exit");
}
public void optionMenu() {
try {
Scanner sc = new Scanner(System.in);
this.option = sc.nextInt();
System.out.println(this.option);
} catch (InputMismatchException e) {
System.out.println("Please enter a number");
optionMenu();
}
switch (this.option) {
case 1:
System.out.println("Game starting...");
break;
case 2:
System.out.println("Loading options");
break;
case 3:
System.out.println("Game exiting...");
System.exit(0);
break;
default:
System.out.println("Enter a valid number (1, 2 or 3");
break;
}
}
}
任何帮助将不胜感激,谢谢!
最佳答案
当您调用 sc.nextInt()
而不首先询问 if (sc.hasNextInt())
时,当最终用户开始输入时,您可能会遇到一些奇怪的行为意外输入,例如字母。在这种情况下,扫描仪不会前进其读取指针,因此您的程序将在读取相同的错误输出时陷入困境。
要解决此问题,请添加一个循环,在尝试再次读取 int
之前“清除”无效条目,如下所示:
while (!sc.hasNextInt()) {
System.out.print("You need to enter an integer.");
sc.nextLine(); // Clear out the bad input
}
int val = sc.nextInt(); // At this point we know that sc.hasNextInt(), because that's the loop condition
另一点是,用迭代来完成的事情并不是一个好主意:对 optionsMenu
的递归调用将累积与次数一样多的调用级别最终用户输入了错误的值,因此理论上,非常执着的用户可以通过重复输入无效数据来强制程序发生堆栈溢出。
使用上面的代码片段将使您无需递归调用 optionsMenu
,也无需捕获输入异常。
关于java - Switch 多次返回相同的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21195381/