我正在制作一款小型文字游戏,要求用户从选项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()),但似乎程序在到达此之前崩溃。
据我所知,每当我键入一个不是Integer的值时,程序就会抛出一个名为InputMismatchException
的运行时异常。
根据Oracle的Java文档:
由扫描器抛出,指示检索到的令牌与预期类型的模式不匹配,或者令牌超出了预期类型的范围。
程序没有达到您的"无效"选项。再试一次!"语句,因为异常是在用户输入后直接抛出的,这意味着,您不能通过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选项。再试一次!"one_answers"re"-调用getSelection()
.