【问题标题】:Issue with Try-Catch and If StatementTry-Catch 和 If 语句的问题
【发布时间】:2014-06-12 20:23:40
【问题描述】:

我目前正在制作一个应用程序,其中用户输入货币价值,价值的变化是用尽可能少的硬币产生的。我已经使程序正常工作,但我在验证时遇到了问题。为了确保只输入货币值,我尝试捕获以确保不输入任何字母,并使用 if 语句确保仅输入带两位小数的数字。为了尝试使它更整洁,我将它们分成两种不同的方法,在我的 main.js 中执行。

这两种方法都能发挥作用。我遇到的问题是,一旦他们产生消息,即使没有输入适当的货币价值,程序的其余部分仍然运行。我如何做到这一点,以便提示用户输入另一个数字。

所有相关代码如下所示。先感谢您。 这是主要的样子:

public static void main(String[] args ) {

    GetValue.AskValue();
    GetValue.CheckValue1();
    GetValue.CheckValue2();
    CalculateChange.Rounding();
    CalculateChange.GenerateDollars();
    CalculateChange.GenerateHalfDollar();
    CalculateChange.GenerateQuarter();
    CalculateChange.GenerateDime();
    CalculateChange.GeneratePennyX2();
    CalculateChange.GeneratePenny();
    CalculateChange.GenerateResults();

}

它们位于一个类中:

static void CheckValue1(){

        Scanner sc = new Scanner(System.in);    
        try {
            System.out.println("Please input an integer:  ");
            //nextInt will throw InputMismatchException
            //if the next token does not match the Integer
            //regular expression, or is out of range
            number =sc.nextDouble();
        } catch(InputMismatchException exception) {
                //Print "This is not an integer"
            //when user put other than integer
            System.out.println("   Please do not type letters");

            AskValue();
       }
       // number = sc.nextDouble();


}
static void CheckValue2(){

        String[] splitter = Double.toString(number).split("\\.");
        splitter[0].length();   // Before Decimal Count
        int decimalLength = splitter[1].length();  // After Decimal Count
        if (decimalLength <= 2){
            java.math.BigDecimal bd = new java.math.BigDecimal(String.valueOf(number));
            Input = Input.add(bd);
        } else{ 
            System.out.println(number +"  Is not a valid number. You may only go to two decimal palces");   
        }

}

【问题讨论】:

  • 请注意,您的方法名称不符合 Java 标准用法。它们会起作用,但如果你使用 Java 约定,你的代码会更容易阅读。
  • 你的代码有问题吗?
  • chrylis 感谢您的评论,我将对其进行更改以遵循命名约定。

标签: java if-statement try-catch


【解决方案1】:

我认为最好的做法是从方法中抛出异常,如下所示:

static void CheckValue1() throws InputMismatchException {
    ...
    number = sc.nextDouble(); // no try-catch
}

static void CheckValue2() throws InputMismatchException {
    if (decimalLength <= 2) {
        ...
    } else {
        throw new InputMismatchException("...");
    }

public static void main(String[] args ) {
    boolean success;
    while (!success)
        try {
            GetValue.AskValue();
            GetValue.CheckValue1();
            GetValue.CheckValue2();
            success = true;
        } catch (InputMismatchException e) {
            ...
        }
    }
}

这样你就可以分离逻辑和错误处理。

【讨论】:

    【解决方案2】:

    改成这样:

    在主要:

    do {
        GetValue.AskValue();
    } while (!GetValue.CheckValue1());
    

    在 CheckValue1 中:

     static boolean CheckValue1(){
    
     Scanner sc = new Scanner(System.in);    
     try {
              System.out.println("Please input an integer:  ");
              number =sc.nextDouble();
              return true;
     }
     catch(InputMismatchException exception) {
              //Print "This is not an integer"
              //when user put other than integer
                System.out.println("   Please do not type letters");
    
    
                return false;
            }
    }
    

    【讨论】:

    • 这项工作感谢您的帮助和非常快速的响应:)
    【解决方案3】:

    一种可能性:再次要求一个值并再次检查。请注意,这可能不是最漂亮的方式。我其实更喜欢

    static void CheckValue1(){
    
        Scanner sc = new Scanner(System.in);    
        try
            {
              System.out.println("Please input an integer:  ");
              //nextInt will throw InputMismatchException
              //if the next token does not match the Integer
              //regular expression, or is out of range
              number =sc.nextDouble();
            }
            catch(InputMismatchException exception)
            {
              //Print "This is not an integer"
              //when user put other than integer
                System.out.println("   Please do not type letters");
    
    
                AskValue();  /////// Ask for new value & check
                CheckValue1();
            }
       // number = sc.nextDouble();
    
    
    }
    static void CheckValue2(){
    
        String[] splitter = Double.toString(number).split("\\.");
        splitter[0].length();   // Before Decimal Count
        int decimalLength = splitter[1].length();  // After Decimal Count
        if (decimalLength <= 2){
        java.math.BigDecimal bd = new java.math.BigDecimal(String.valueOf(number));
        Input = Input.add(bd);
        }
        else{   
            System.out.println(number +"  Is not a valid number. You may only go to two decimal palces");   
            AskValue();   ///////////// Ask for new value & check
            CheckValue1();
            CheckValue2();
        }
    
     }
    

    【讨论】:

      最近更新 更多