Java For循环在异常后重置
目前,我正在做一个选择题测验。但是我被这个问题困住了。异常发生后,我的for循环重置,基本上返回到0。还有别的办法解决这个问题吗?或者我的代码在逻辑上是错误的?每当抛出异常时,for循环都会重置。 例如,我在第5个问题上遇到一个异常,For循环返回到0Java For循环在异常后重置,java,exception,Java,Exception,目前,我正在做一个选择题测验。但是我被这个问题困住了。异常发生后,我的for循环重置,基本上返回到0。还有别的办法解决这个问题吗?或者我的代码在逻辑上是错误的?每当抛出异常时,for循环都会重置。 例如,我在第5个问题上遇到一个异常,For循环返回到0 do{ try { Scanner A = new Scanner (System.in); for (int x = 0; x < Questions.length;x++){ loop = x;
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);
do{
试一试{
扫描仪A=新的扫描仪(System.in);
for(int x=0;x
当您抛出异常时,您会返回到do-while循环的开始,因为try块就是从那里开始的。如果您不想在异常中重置循环,请在for循环中放置try-catch块。您的catch
在哪里?如果你在循环外处理异常,那么当你处理异常时,你就在循环外。你说的“for循环重置”是什么意思?如果发生异常,您只需中断循环。为什么要抛出这些异常?只要将错误处理代码移到else if
块中即可。