java - 尝试 Catch Exception 未按预期工作
问题描述
我的InputMismatchException
行不通。相反,一个工作是我从另一个名为InvalidLetterException
. 如果我输入一个数字,则执行 catch 的异常InvalidLetterException
不是 the,InputMismatchException
因为我输入的是一个整数,一种不同的数据类型。我暗示我的if-else
陈述有问题,但我不知道该怎么做。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ",
"What is the capital of the Philippines? ", "Who is the current president of the Philippines? ",
"What is the capital of Japan? ", "What is 2 + 3? ",
"What is 9 + 1?", "What is the capital of the United States? ",
"What is 10 + 10? ", "How many hand fingers do humans have? "};
String choices[] = {"a","b","c"};
int x = 0;
int y = 0;
try {
while(x<=9) {
System.out.println("No." + (x+1) + "." + questions[x]);
String answer = scan.next();
x++;
if(answer.equals(choices[0])) {
scan.nextLine();
} else if (answer.equals(choices[1])) {
scan.nextLine();
} else if (answer.equals(choices[2])) {
scan.nextLine();
} else if (!answer.equals(choices)) {
throw new InvalidLetterException();
}
}
} catch(InvalidLetterException e) {
System.out.println(e.getMessage());
System.out.println(); //Spacing
System.out.println("You can try again.");
System.out.println(); //Spacing
do {
System.out.println("No." + (y+1) + "." + questions[y]);
scan.next();
y++;
}while(y<=9);
} catch (InputMismatchException i) {
System.out.println("Please don't enter numbers.");
}
}
解决方案
好吧,InputMismatchException
永远不能在你的try
街区内抛出一个。如果你会打电话nextInt()
,那么它会。但next()
不要期望输入是某种格式,你可以输入任何你想要的。
!answer.equals(choices)
如果其他陈述是错误的,这总是正确的if
,因此有效地,它可以被替换为 just else
。
推荐阅读
- javascript - 使用 SocketIO 中的房间查找用户存在
- excel - 我需要读取一个 Excel 文件,解析并将结果写入另一个 Excel 文件
- java - 如何在 SQL 中调用 Java 方法?(注意 - 不是 Java 到 SQL,而是 SQL 到 Java)
- bash - 意外标记';;'附近的 BASH 脚本语法错误
- spring - Spring @Async 多线程问题
- r - R闪亮的数字输入步骤验证
- android - 下载 storageReference 到 drawable
- r - R重塑数据和总结信息
- python - 我的 API 用 beautifulSoup4 和 python 解析数据太慢了
- service-worker - create-react-app 的服务工作者不会忽略 url