如何忽略用户的无效输入并再次提示相同的问题?

时间:2019-04-21 09:23:17

标签: java while-loop try-catch java.util.scanner user-input

当用户输入无效值(例如字符串或字符)时,程序应忽略它并再次显示上一个问题。到目前为止,我只能在捕获无效输入时使程序退出。

有效输入为int和“ q”,用户决定退出。

 public static void partB() {
 int score = 0;
 int correct = 0;
 int done = 0;
 Scanner scan = new Scanner(System.in);
 try {
     while (true) {
         int num1 = (int) (Math.random() * 20);
         int num2 = (int) ((Math.random() * 20) + 1);
         System.out.printf("%d  %% %d = ?\n", num1, num2);
         if (scan.hasNext("q")) break;
         if (scan.nextInt() == (num1 % num2)) {
             score += 20;
             done += 1;
             correct += 1;
             System.out.println("Correct answer,current score :" + score 
     + ",performance: "
                     + correct + "/" + done);
         } else {
             done += 1;
             System.out.println("Incorrect answer, Current score:" + 
      score
                     + ", performance: " + correct + "/" + done);
         }
     }
 } catch (InputMismatchException e) {
       System.out.println("invalid input"); //but this terminate program

    }
     System.out.println("Finish");
  }

代码应该像这样运行:

18 % 12 = ?
6
Correct answer, Current score: 20, performance: 1/1
14 % 16 = ?
a
Invalid input
14 % 16 = ?
14
Correct answer, Current score: 40, performance: 2/2
20 % 4 = ?
q
Finish.

2 个答案:

答案 0 :(得分:0)

您需要在try-catch块内移动while。另外,当存在InputMismatchException时,您必须完成读取行(因为您使用Scanner#nextInt而不是Scanner#nextLine),并将变量(repeatValue)设置为{{1} }。使用此变量,您可以决定是需要生成新值还是使用先前的值。

查看running here

true

答案 1 :(得分:0)

您的try / catch块位置错误。它必须在循环内部,以避免使用无效输入破坏循环:

  public static void main(String[] args) {
    int score = 0;
    int correct = 0;
    int done = 0;
    Scanner scan = new Scanner(System.in);
    while (true) {
      int num1 = (int) (Math.random() * 20);
      int num2 = (int) ((Math.random() * 20) + 1);
      System.out.printf("%d  %% %d = ?\n", num1, num2);
      if (scan.hasNext("q")) break;
      try {
        if (scan.nextInt() == (num1 % num2)) {
          score += 20;
          done += 1;
          correct += 1;
          System.out.println(
              "Correct answer,current score :" + score + ",performance: " + correct + "/" + done);
        } else {
          done += 1;
          System.out.println(
              "Incorrect answer, Current score:"
                  + score
                  + ", performance: "
                  + correct
                  + "/"
                  + done);
        }
      } catch (InputMismatchException e) {
        done += 1;
        scan.nextLine();
        System.out.println("invalid input"); // but this terminate program
      }
    }
    scan.close();
    System.out.println("Finish");
  }

您必须在catch块中清空扫描仪,以避免无限循环。