【问题标题】:Looping around a try catch循环尝试捕获
【发布时间】:2013-12-15 18:56:04
【问题描述】:

在下面的代码中,我试图让程序捕获来自用户的无效输入的异常,但仍然允许程序在捕获异常后循环回到方法的开头。但是,在我的示例中,一旦出现异常,程序就会终止。我该如何纠正这个问题?提前非常感谢!

public static void add() {
    // Setting up random
    Random random = new Random();

    // Declaring Integers
    int num1;
    int num2;
    int result;
    int input;
    input = 0;
    // Declaring boolean for userAnswer (Defaulted to false)
    boolean correctAnswer = false;
    do {
        // Create two random numbers between 1 and 100
        num1 = random.nextInt(100);
        num1++;
        num2 = random.nextInt(100);
        num2++;

        // Displaying numbers for user and getting user input for answer
        System.out.println("Adding numbers...");
        System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
        result = num1 + num2;

        do {
            try {
                input = scanner.nextInt();
            } catch (Exception ex) {
                // Print error message
                System.out.println("Sorry, invalid number entered for addition");
                // flush scanner
                scanner.next();
                correctAnswer=false;
            }
        } while (correctAnswer);

        // Line break for code clarity
        System.out.println();

        // if else statement to determine if answer is correct
        if (result == input) {
            System.out.println("Well done, you guessed corectly!");
            correctAnswer = true;
        } else {
            System.out.println("Sorry incorrect, please guess again");
        }
    } while (!correctAnswer);

}// End of add

【问题讨论】:

  • 你确定异常是在try/catch里面抛出的吗?
  • 正如@marsze 所说,错误可能发生在try... catch... 之外,在这种情况下它不会被捕获并将终止(除非在其他地方捕获)。如果你已经确定它在这段代码中,我猜scanner.next(); 触发了第二个异常,因为它在你的 catch 语句中,所以它失败了。您遇到了什么异常?
  • 你内心的 do/while 似乎永远不会爆发。什么时候将 correctAnswer 设置为 true

标签: java loops exception try-catch


【解决方案1】:

我不太确定异常部分,但您是否考虑过仅使用 if 语句?

Scanner 有一个方法 'hasNextInt' 可以用来检查输入是否为 na int。例如:

    Scanner scan = new Scanner(System.in);
    int i=0;
    boolean correctAnswer = false;
    while(correctAnswer == false){
        if(scan.hasNextInt()){
            i = scan.nextInt(); correctAnswer = true;
        }else{ System.out.println("Invalid entry");
               correctAnswer = false;
               scan.next();
        }
    System.out.println(i);
    }

很抱歉,它实际上并没有直接回答您的问题,但我认为您可能也想知道这种可能的方式。 :)

【讨论】:

    【解决方案2】:

    您可以使用 hasNextInt() 方法代替抛出异常,如果令牌是数字,则返回 true。 但是如果你想绝对使用 try catch 块,你必须删除scanner.next() 指令,因为当缓冲区上没有可用的内容时,它会抛出一个NoSuchElementException

    【讨论】:

      【解决方案3】:

      我认为我提供的解决方案可以改进,但这是修复代码的简单修改:(只需添加新的条件变量以检查是否需要进一步的输入/ans 尝试)

      希望对您有所帮助 - MAK

      public class StackTest {
      
          private static Scanner scanner = new Scanner(System.in);
      
          public static void main(String[] args) throws InterruptedException{
              // Setting up random
              Random random = new Random();
      
              // Declaring Integers
              int num1;
              int num2;
              int result;
              int input;
              input = 0;
              // Declaring boolean for userAnswer (Defaulted to false)
              boolean correctAnswer = false;
              //MAK: Add new condition for checking need of input
              boolean needAnswer = true;
              do {
                  // Create two random numbers between 1 and 100
                  num1 = random.nextInt(100);
                  num1++;
                  num2 = random.nextInt(100);
                  num2++;
      
                  // Displaying numbers for user and getting user input for answer
                  System.out.println("Adding numbers...");
                  System.out.printf("What is: %d + %d? Please enter answer below",
                          num1, num2);
                  result = num1 + num2;
      
                  while(needAnswer){
                      try {
      
                          input = scanner.nextInt();
                          needAnswer = false;
                      } catch (Exception ex) {
                          // Print error message
                          System.out.println("Sorry, invalid number entered for addition");
                          // flush scanner
                          scanner.next();
                          needAnswer = true;
                      }
                  } ;
      
                  // Line break for code clarity
                  System.out.println();
      
                  // if else statement to determine if answer is correct
                  if (result == input) {
      
                      System.out.println("Well done, you guessed corectly!");
                      correctAnswer = true;
                  } else {
                      System.out.println("Sorry incorrect, please guess again");
                      needAnswer = true;
                  }
              } while (!correctAnswer);
      
          }
      }
      

      【讨论】:

      • 以防万一有人没有注意到,如果你输入 not int 作为答案会抛出异常:)
      【解决方案4】:

      如果你想拥有以下:

      1) 询问用户 x + y 是多少
      2) 让用户回答
      3)如果答案无效(例如用户输入“www”),让用户再次输入他对问题1)的答案

      你应该用以下内容替换你的内部 do-while 循环:

                  boolean validInput = true;
              do {
                  try {
                      input = scanner.nextInt();
                  } catch (Exception ex) {
                      // Print error message
                      System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
                      // flush scanner
                      scanner.next();
                      validInput = false;
                  }
              } while (!validInput);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-02
        相关资源
        最近更新 更多