【问题标题】:For loop resets after an exception异常后for循环重置
【发布时间】: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 块中即可。

标签: java exception


【解决方案1】:

当您抛出异常时,您会回到 do while 循环的开头,因为那是您的 try 块开始的地方。如果您不想在异常中重置循环,请在 for 循环中放置一个 try catch 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2022-01-16
    • 1970-01-01
    • 2022-01-19
    • 2014-07-01
    • 2013-07-30
    相关资源
    最近更新 更多