我需要帮助 使用错误的用户输入进行异常处理。我正在创建一个基于文本的游戏,它欢迎用户,然后进入主菜单。然后它告诉用户选项,然后寻找用户输入。出于某种原因,每当我输入 1 或 2 时,它都会显示:“您的输入无效,请重试”并返回选择。我不知道我到底哪里出错了,希望有人能帮助我。此外,它也不会捕获不匹配异常。希望你能帮忙!谢谢,山丹
public static void main(String[] args) {
System.out.println("Welcome to Spec Ops!");
System.out.println("Please state your name:");
Scanner name = new Scanner(System.in);
String Name = name.next();
System.out.println("Hello "+Name);
mainMenu();
}
public static void mainMenu() {
System.out.println("1. Story Mode");
System.out.println("2. Infinant Combat");
Scanner input = new Scanner(System.in);
Object Selection = input.nextInt();
boolean validOption = true;
Integer x;
try {
x = (Integer)Selection;
} catch(ClassCastException cce){
System.out.println("Your input is invalid, please try again");
validOption = false;
} catch(InputMismatchException ime){
System.out.println("Your input is invalid, please try again");
validOption = false;
}
if(validOption) {
System.out.println("Hello!");
}
else {
mainMenu();
}
}
}