【发布时间】:2019-01-31 17:50:35
【问题描述】:
目前,我正在做多项选择测验。但我被这个问题困住了。发生异常后,我的for循环重置并基本返回0。有没有其他方法可以解决这个问题?还是我的代码在逻辑上是错误的?每当抛出异常时,for 循环都会重置。 例如,我在第 5 个问题上,发生了异常,for 循环回到 0。
do{
try {
Scanner A = new Scanner (System.in);
for (int x = 0; x < Questions.length;x++){
loop = x;
System.out.println(Questions[x]);
System.out.println(Choices[x]);
System.out.println("");
System.out.print("Answer: ");
UAnswer = A.nextLine();
if (UAnswer.equalsIgnoreCase("A") || UAnswer.equalsIgnoreCase("B") || UAnswer.equalsIgnoreCase("C")){
if (UAnswer.equalsIgnoreCase(AnswerKey[x])){
System.out.println("");
System.out.println("Correct Answer!\n");
Score++;
}
else {
System.out.println("");
System.out.println("Wrong! The correct answer is: " + AnswerKey[x] + "\n");
}
}
else if (UAnswer.equalsIgnoreCase("")){
throw new NullPointerException();
}
else {
throw new InputMismatchException();
}
}
}
catch(InputMismatchException ime){
System.out.println("");
System.out.println("Invalid input! Please type A,B,C!\n");
}
catch(NullPointerException b){
System.out.println("");
System.out.println("You did not input any answer.\n");
}
}while(loop != 9);
【问题讨论】:
-
你的
catch呢?如果您在循环外处理异常,那么当您处理异常时,您将处于循环之外。 -
“for 循环重置”是什么意思?如果发生异常,您只需跳出循环即可。
-
为什么要抛出这些异常?只需将错误处理代码移动到
else if块中即可。