【问题标题】:try catch in a do while loop尝试在 do while 循环中捕获
【发布时间】:2017-07-27 11:02:06
【问题描述】:

程序要求用户输入 double num 1 和 double num 2 如果有异常,我希望它再次要求输入 num 1 和 num 2

public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    double num1, num2;
    int error = 0;
    int text;
    System.out.print("Enter 4 ");
        text = sc.nextInt();

    do{

        try{

    if(text == 4){
            System.out.print("Enter number 1: ");
            num1 = sc.nextDouble();
            System.out.print("Enter number 2: ");
            num2 = sc.nextDouble();
            double quotient = num1/num2;
            System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
            }
        }catch(Exception ex){ 
            System.out.println("You've entered wrong input");
                error = 1;
        }                                  

          }while(error == 1);
}

然后,当我尝试代码时,它是否会通过在 num1 或 num 2 中输入字符串来捕获异常,我有这个无限循环: Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input

【问题讨论】:

  • 请提供minimal reproducible example(注意“完整”位)。
  • 你从哪里得到那个双倍的?
  • 您的代码将受益于声明和(重新)使用从用户获取输入直到用户输入有效数据的单独方法。

标签: java exception-handling try-catch do-while


【解决方案1】:

你需要在循环内重置error变量

do {
    error = 0;
    //...
} while(error == 1);

【讨论】:

  • 仍有循环
  • @Pon 您需要在do while 循环中添加error = 0;
  • 我确实把它放在了 do while 循环中,但它仍然循环
  • @Pon catch 中捕获的异常是什么?
  • InputMismatchException 因为我试图将字符串输入到双精度数据类型中
【解决方案2】:

没有必要使用异常处理。只需使用Scanner.hasNextDouble()方法判断实际用户输入是否为double,否则继续循环。

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double num1, num2;
        num1 = readDouble(1, sc);
        num2 = readDouble(2, sc);
        double quotient = num1/num2;
        System.out.println("The Quotient of " + num1 + "/" + num2 + " = " + quotient);
    }

    private static double readDouble(int i, Scanner sc) {
        while (true) {
            System.out.print("Enter number " + i + ": ");
            if (!sc.hasNextDouble()) {
                System.out.println("You've entered wrong input");
                sc.next();
                continue;
            }
            break;
        }
        return sc.nextDouble();
    }
}

【讨论】:

  • 很抱歉没有把它放在代码中,但是有多个 else if 在那里,因为我希望用户定义他/她想要做的方法。我尝试了您通过添加布尔继续注释的代码并中断它没有任何错误但是当我输入字符串而不是双精度时循环没有开始
  • 我错过了sc.next();
  • 修复它。
【解决方案3】:

它在 C# 中,但比较相似:)

public class Program
{
  private static double ReadUserInput (string message) 
  {
    // This is a double
    // The '?' makes it nullable which is easier to work with
    double? input = null;

    do 
    {
      // Write message out
      Console.Write(message);
      // Read answer
      var inputString = Console.ReadLine();
      // Temp variable for the number
      double outputNumber = 0;
      // Try parse the number
      if (double.TryParse(inputString, out outputNumber))
      {
        // The number was parsable as a double so lets set the input variable
        input = outputNumber;
      }
      else
      {
        // Tell the user the number was invalid
        Console.WriteLine("Sorry bud, but '" + inputString + "' is not a valid double");
      }
    } 
    while (input == null); // Keep running until the input variable is actually set by the above

    // Return the output
    return (double)input;
  }

  public static void Main()
  {
    // Read a number
    var num1 = ReadUserInput("Enter number 1:");
    // Read another number
    var num2 = ReadUserInput("Enter number 2:");
    // Show the calculation
    Console.WriteLine("Answer: " + (num1*num2));
  }
}

Demo

对于实际代码(在 JAVA 中):

public class JavaFiddle 
{
  public static void main (String[] args) 
  {
    // Read a number
    Double num1 = ReadUserInput("Enter number 1:");
    // Read another number
    Double num2 = ReadUserInput("Enter number 2:");
    // Show the calculation
    System.out.println("Answer: " + (num1*num2));
  }

  public static Double ReadUserInput (String message) 
  {
    java.util.Scanner inputScanner = new java.util.Scanner(System.in);
    Double input = null;

    do 
    {
      // Write message out
      System.out.println(message);
      // Read answer
      String inputString = inputScanner.nextLine();
      try 
      {
        // Try parse the number
        input = Double.parseDouble(inputString);
      } 
      catch (NumberFormatException e) 
      {
        // Tell the user the number was invalid
        System.out.println("Sorry bud, but '" + inputString + "' is not a valid double");
      }
    } 
    while (input == null); // Keep running until the input variable is actually set by the above

    // Return the output
    return input;
  }
}

【讨论】:

  • 没有C#标签有问题。为什么你决定发布无用的答案?
  • 这看起来是个不错的解决方案,但你应该写在java
  • 更多的是过程以及如何以 OOP 样式编写此过程以及过程运行的方式是我要回答的地方而不是代码。 JAVA 和 C# 之间没有太大区别,但由于我已经很久没有做过 JAVA 了,所以我宁愿发布工作代码,也不愿发布一些可能有效的代码,或者如果它不起作用,则让某人感到困惑——这更糟。我会考虑用 JAVA 重写以更符合 Q :)
【解决方案4】:

您可能想测试是否没有错误:

}while(error != 1);

}while(error == 0);

【讨论】:

    【解决方案5】:

    如果输入无效,您将需要一个调用自身的输入方法。

    double getInput(Scanner sc) {
        try {
            double num = sc.nextDouble();
            return num;
        } catch(Exception ex) { 
            System.out.println("You've entered wrong input");
            return getInput(sc);
        }    
    }
    

    并在您的其他方法中调用此方法两次。

    【讨论】:

      【解决方案6】:

      它可能看起来很难看,但这是一种方法

        do
        {
          if(...)
          {
      
            boolean successReading = false;
            while(!successReading)
            {
              try
              {
                System.out.print("Enter number 1: ");
                num1 = sc.nextDouble();
                System.out.print("Enter number 2: ");
                num2 = sc.nextDouble();
      
                successReading = true;
      
                double product = num1*num2;
              }
              catch(Exception e)
              {
                successReading = false;  
              }
            }
      
          }
        }while(...)
      

      【讨论】:

      • 嘿,这是一个菜鸟问题,但最后一段时间里面是什么?
      • 保持do while 循环的条件。但是让我问你一个问题,为什么要写这个if(text == 4){
      【解决方案7】:

      您需要在catch 块内添加sc.next();

      nextDouble 方法在出现异常时不会清除缓冲区。所以下次你调用它时你会得到同样的错误,因为旧的输入仍然在缓冲区中。

      您还需要在循环开始时重置 error 标志。

      【讨论】:

      • 然后将其标记为已接受。它有助于为与您有相同问题的人找到正确的答案。
      【解决方案8】:

      您必须将 sc.next(); 放在 catch 中,这样它才能清除您的扫描仪变量并要求输入

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 2013-12-15
        • 2014-03-17
        • 1970-01-01
        相关资源
        最近更新 更多