发生异常后进行循环重置

时间:2019-01-31 17:50:35

标签: 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;
      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);

1 个答案:

答案 0 :(得分:0)

在引发异常时,您将返回到do while循环的开始,因为这是try块的开始位置。如果您不想在异常中重置循环,请将try catch块放入for循环中。