简体   繁体   中英

Exception Thread in Do-While Loop

I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.

For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.

As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?

If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.

    import java.util.Scanner;

 public class InterestCalculator
 {
    public static void main(String[] args)
 {
  Scanner scannerObject = new Scanner(System.in);


   Scanner input = new Scanner(System.in);

   int quartersDisplayed;
   double b, IR;


    do
  {
     Scanner keyboard=new Scanner(System.in);
     System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
     quartersDisplayed = keyboard.nextInt();

     System.out.println("Next enter the starting balance. ");
     System.out.println("This input must be greater than zero: ");
     b = keyboard.nextDouble();


     System.out.println("Finally, enter the interest rate ");
     System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
     IR = keyboard.nextDouble();


     System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);         
     System.out.println("You also entered the starting balance of: " + b);
     System.out.println("Finally, you entered the following of interest rate: " + IR);
     System.out.println("If this information is not correct, please exit the program and enter the correct information.");


     double quarterlyEndingBalance = b + (b * IR/100 * .25);
     System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);  
     System.out.println("Do you want to continue?"); 
     String yes=keyboard.next("yes");
     if (yes.equals(yes))
     continue;
     else
     break;

        }
        while(true);
  }
}

So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.

Note : I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment

import java.util.Scanner;

public class InterestCalculator {

public static void main(String[] args) {
//      EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
//      Scanner scannerObject = new Scanner(System.in);

        Scanner input = new Scanner(System.in);

        //EDIT: defining userResponse outside the loop so we can use it everywhere inside
        String userResponse = null;

        do {
            //EDIT: moved the variables inside the loop so that they are reset each time we start over.
            //EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
            int quartersDisplayed = -1;
            //EDIT: gave your variables more meaningful names that conform to java standards
            double startingBalance = -1, interestRate = -1;

            //EDIT: you don't need a second Scanner, just use the one you already have.
//          Scanner keyboard = new Scanner(System.in);

            do{
                System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
                userResponse  = input.next();
                try{
                    quartersDisplayed = Integer.parseInt(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                if(quartersDisplayed <= 0 || quartersDisplayed > 10){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            do{
                System.out.println("Enter the starting balance (must be greater than zero): ");
                userResponse  = input.next();
                try{
                    startingBalance = Double.parseDouble(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                if(startingBalance <= 0){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            do{
                System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
                userResponse  = input.next();
                try{
                    interestRate = Double.parseDouble(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                //Note: I assume twenty percent is represented as 20.0 here
                if(interestRate <= 0 || interestRate > 20){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            System.out.println("You have entered the following amount of quarters: "
                            + quartersDisplayed);
            System.out.println("You also entered the starting balance of: " + startingBalance);
            System.out.println("Finally, you entered the following of interest rate: "
                            + interestRate);
            System.out.println("If this information is not correct, please exit the program and enter the correct information.");

            double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
            System.out.println("Your ending balance for your quarters is "
                    + quarterlyEndingBalance);
            System.out.println("Do you want to continue?");
            //EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
            userResponse = input.next();
//          EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
//          if (userResponse.equals(userResponse))
            if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
                continue;
            else
                break;

        } while (true);

Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.

This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.

Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.

You can do something like this in your do/while loop:

do
{
    Scanner keyboard = new Scanner(System.in);

    do
    {
        System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
        quartersDisplayed = keyboard.nextInt();
    }
    while (quartersDisplayed < 1 || quartersDisplayed > 10);

    System.out.println("Next enter the starting balance. ");
    do
    {
        System.out.println("This input must be greater than zero: ");
        b = keyboard.nextDouble();
    }
    while (b < 1);

    // rest of code ... 
}

With the Scanner#hasNextInt (and the equivalent for double ), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.

However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here .

I didn't include all of your code, only the part in question. Here's my take on it:

import java.util.Scanner;

public class InterestCalculator {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int quartersDisplayed = -1;
        double b = -1.0;
        double IR = -1.0;

        do {
            do {
                System.out.println("Enter the number of quarters.");
                if(keyboard.hasNextInt()) {
                    quartersDisplayed = keyboard.nextInt();
                    keyboard.nextLine(); //important
                } else {
                    System.out.println("You need to enter an integer.");
                    continue;
                }
            } while(quartersDisplayed < 1 || quartersDisplayed > 10);

            do {
                System.out.println("Enter the starting balance.");
                if(keyboard.hasNextDouble()) {
                    b = keyboard.nextDouble();
                    keyboard.nextLine();
                } else {
                    System.out.println("You must enter a number.");
                    continue;
                }
            } while(b <= 0);

            do {
                System.out.println("Enter the interest rate.");
                if(keyboard.hasNextDouble()) {
                    IR = keyboard.nextDouble();
                    keyboard.nextLine();
                } else {
                    System.out.println("You must enter a number.");
                    continue;
                }
            } while(IR <= 0 || IR > 20.0);

            //... rest of code
        } while(true);
    }
}

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