简体   繁体   English

Try-Catch和If语句的问题

[英]Issue with Try-Catch and If Statement

I am currently producing an application in which a user input a monetary value and the change of the value is the produced with as few coins as possible. 我目前正在开发一个应用程序,其中用户输入货币值,并且值的变化是使用尽可能少的硬币生成的。 I have made the program work but I am having problems with the validation. 我已经使该程序正常工作,但是验证存在问题。 To ensure that only monetary values are entered i have a try catch to ensure no letters are entered and an if statement to ensure that numbers are only entered with two decimal places. 为了确保仅输入货币值,我尝试了一次尝试以确保不输入字母,并使用if语句来确保仅输入两位小数。 In order to try an make it tidier I have split these into two different methods which are executed in my main. 为了尝试更整齐,我将它们分为两种在我的main中执行的不同方法。

Both of these methods do the job and work. 这两种方法都能完成工作。 The problem that I have is that once they produce the message the rest of the program still runs even though no proper monetary value has been entered. 我的问题是,即使他们没有输入正确的货币价值,一旦他们产生了消息,程序的其余部分仍然可以运行。 How do i make it so that the user is prompted to enter another number. 我如何做到这一点,以便提示用户输入另一个数字。

All of the relevant code is shown below. 所有相关代码如下所示。 Thank you in advance. 先感谢您。 This is what the main looks like: 这是主要的样子:

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();

}

These are located in one class: 这些位于一类中:

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

}

I think that the best practice is to throw exception from methods, something like this: 我认为最佳实践是从方法中抛出异常,如下所示:

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) {
            ...
        }
    }
}

This way you separate logic and error handling. 这样,您就可以将逻辑和错误处理分开。

Change it like this: 像这样更改它:

In Main: 在主要:

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

In 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;
        }
}

One possibility: Ask for a value again and check again. 一种可能:再次要求输入值并再次检查。 Note this may not be the most beautiful way possible. 请注意,这可能不是最美丽的方法。 I would actually prefer 我实际上更喜欢

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

 }

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

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