简体   繁体   中英

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. In order to try an make it tidier I have split these into two different methods which are executed in my 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:

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

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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