简体   繁体   English

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

[英]How to ignore user invalid input and re-prompt the same question?

When the user input an invalid value, like a String or character, the program should ignore it and show the previous question again.当用户输入无效值时,如字符串或字符,程序应忽略它并再次显示上一个问题。 So far I can only make the program quit when it catch invalid input.到目前为止,我只能让程序在捕获无效输入时退出。

Valid inputs are int and "q", which user decided to quit.有效输入是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");
  }

And the code is supposed to run like this:代码应该像这样运行:

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.

You need to move the try-catch inside the while block.您需要将try-catch移动到while块内。 Also when there is a InputMismatchException you have to finish reading the line (because you used Scanner#nextInt instead of Scanner#nextLine ) and set a variable ( repeatValue ) to true .此外,当出现InputMismatchException您必须完成读取该行(因为您使用了Scanner#nextInt而不是Scanner#nextLine )并将变量( repeatValue )设置为true With this variable you can decide whether you need to generate new values or use the previous ones.使用此变量,您可以决定是需要生成新值还是使用以前的值。

See it running here :看到它在这里运行

public static void main(String[] args) {
    int score = 0;
    int correct = 0;
    int done = 0;
    Scanner scan = new Scanner(System.in);
    boolean repeatValue = false;
    int num1 = 0; // put values outside while in order to re-use them when we need to repeat the same question
    int num2 = 0;
    while (true) {
        try {
            // if the user input was incorrect (repeatValue = true), use old the previous values for num1 and num2
            num1 = repeatValue ? num1 : (int) (Math.random() * 20);
            num2 = repeatValue ? num2 : (int) ((Math.random() * 20) + 1);
            System.out.printf("%d  %% %d = ?\n", num1, num2);
            repeatValue = false;  // restore flag state
            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");
            scan.next();
            repeatValue = true; // flag set to use the same values as before
        }
    }
    System.out.println("Finish");
}

Your try/catch block is at the wrong position.您的 try/catch 块位于错误的位置。 It has to be inside your loop to avoid breaking the loop with an invalid input:它必须在您的循环内,以避免使用无效输入破坏循环:

  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");
  }

You have to empty the Scanner in the catch block to avoid an infinite loop.您必须清空 catch 块中的 Scanner 以避免无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM