Calculating the cost of departure

For this program, we have to calculate the total price of items entered by the user. We use methods to get the double range and a method that asks the user if they want to continue. Here are the methods I am using:

public static double getRangedDouble(Scanner src, String prompt, double lo, double hi)
    {
        double retVal = lo - 1;
        String trash;
        do
        {
            System.out.print(prompt + " " + lo + " - " + hi);
            if(src.hasNextInt())
            {
                retVal = src.nextInt();
            }
            else
            {
                trash = src.nextLine();
            }
        }while(retVal < lo || retVal > hi);

        return retVal;
    }

    public static Boolean getYNConfirm(Scanner src, String prompt)
    {
        String input = "";
        boolean done=true;

        System.out.println(prompt + " Y or N");
        while(!done)
        {
            input = src.nextLine();
            if(input.equalsIgnoreCase("Y"))
            {
                done=true;
            }
            else if(input.equalsIgnoreCase("N"))
            {
                done=false;
            }
            else
            {
                System.out.println("Y or N");
            }
        }
        return done;
    }

      

And here's the description straight from my assignment:

At a $ 10 store, nothing is more than $ 10.00. Prompt the user for the price of their item (0.50 cents to 9.99 US dollars) using getRangedDouble and keep entering items if they indicate they are using the getYNConfirm method more. display the total value of the item (s) to 2 decimal places using printf.

I know how to use the methods in the program, but I have no idea how to get the getYNConfirm method or how to calculate the total price when the user enters the individual prices. Any help would be greatly appreciated.

+3


source to share


3 answers


Okay, so let's jump into your question:

At a $ 10 store, nothing is more than $ 10.00. Prompt the user for the price of your item (0.50 cents to 9.99 US dollars) using the getRangedDouble method and keep entering items as long as they indicate they are using the getYNConfirm method more. Display the total cost of the item (s) to 2 decimal places using printf.

The first thing to do with any coding issue at this level is to break it down into its component parts. About this question:

  • You can ask the user for the price of the product (check)
  • Be able to ask the user if they have another input element (check-ish ... see below).
  • Complete the above 2 steps until the second value is true (TODO)
  • Be able to sum the values ​​specified at each price cycle step (TODO)

For step 1, we have getRangedDouble(...)

that checks. It is copied here for convenience:

public static double getRangedDouble(Scanner src, String prompt, double lo, double hi){
  double retVal = lo - 1;
  String trash;
  do{
    System.out.print(prompt + " " + lo + " - " + hi);
    if(src.hasNextInt()){
       retVal = src.nextInt();
    } else {
       trash = src.nextLine();
    }
  } while(retVal < lo || retVal > hi);
  return retVal;
}

      

For step 2, we have the method getYNConfirm(...)

shown here:

public static Boolean getYNConfirm(Scanner src, String prompt){
  String input = "";
  boolean done=true;
  System.out.println(prompt + " Y or N");
  while(!done){
    input = src.nextLine();
    if(input.equalsIgnoreCase("Y")){
      done=true;
    } else if(input.equalsIgnoreCase("N")) {
      done=false;
    } else {
      System.out.println("Y or N");
    }
  }
  return done;
}

      

Unfortunately, there is a logical error in this. You have initialized to true and the while loop exceeded the while (! Done) condition. So the first time it's time (! True) -> while (false), which fails. This way the while loop will never be entered, so we return true every time you call the method. To fix this, consider what you do when you see "Y" - you end up returning true. Your method goes through the motion of the first cycle, but we can just skip that step and go straight to returning the truth. So, consider this version of the method getYN

...:



public static boolean getYNConfirm(Scanner src, String prompt){
  String input = "";
  System.out.println(prompt + " Y or N");
  while(true){ //Loops forever until a return or break statement 
    input = src.nextLine();
     if(input.equalsIgnoreCase("Y")){
       return true;
     } else if(input.equalsIgnoreCase("N")) {
       return false;
     } else {
       System.out.println("Y or N");
     }
   }
}

      

This is in line with the intent of your original version of the method, without a boolean error.

So now we get to our big final - write a method using the above two methods as helpers that loops and continually asks the user for higher prices, summing them up. Let's write this method like main(String[] args)

so that we can run it and see what happens.

We want to use a loop here to allow the user to keep entering prices until they are met. We can simulate our problem with psuedocode like this:

while(user not done inputting prices){
    get next price
    add price to sum of prices
    ask the user if they would like to continue
}
print sum of prices

      

Just like you can call a built-in method and save the output results such as rentVal = src.nextInt()

, you can do the same with methods you write. For example, we might ask the user to enter the next price using getRangedDouble(...)

. According to the method header we wrote, this returns a type value double

, so when we save the output of this call, it should be in a variable double

:double nextPrice = getRangedDouble(...);

If psuedocode makes sense, the following code is actually relatively simple:

public static void main(String[] args){

  Scanner s = new Scanner(System.in); //Allow for reading user input from console

  boolean looping = true; //True so long as the user isn't done inputting prices.
                          //Initially true so that at least one price is entered
  double sum = 0.0;       //The sum of prices thus far
  while(looping){
    double nextPrice = getRangedDouble(s, "Enter a price in the range", 0.5, 10.0);
    sum = sum + nextPrice; //Add the price into the sum
    looping = getYNConfirm(s, "Add another item to your cart?");
  }
  System.out.println(String.format("%.2f", sum)); //Prints sum, limited to 2 decimal places
}

      

+1


source


I don't understand why this is the wrong answer. I feel like the code is very clear here. I've added some additional arguments, but I'm happy to explain that there is something wrong with it.

So the code looks like this.

public static double getRangedDouble(Scanner src, String prompt, double lo, double hi)
{
    boolean valid = false;
    while( !valid ) {
        System.out.print(prompt + " " + lo + " - " + hi);
        if(src.hasNextInt())
            retVal = src.nextInt();
        else
            src.nextLine();

        if( retVal < 10 && retVal > 0.5 )
            valid = true;
    }

    return retVal;
}

public static Boolean getYNConfirm(Scanner src, String prompt)
{
    String input;
    boolean done = false;
    double total;
    DecimalFormat df=new DecimalFormat("#.##");

    while(!done) {
        System.out.println("Y or N");
        input = src.nextLine();

        if(input.equalsIgnoreCase("Y"))
            done=true;
        else if(input.equalsIgnoreCase("N")) {
            done=false;
            total += getRangedDouble( file, "Specify the price between:", 0.50, 9.99);
            System.out.println( "The total is:" + df.format( total ) );
        }
    }
    return done;
}

      

Basically, you want to call getRangedDouble to ask the user for a price. You do this by adding a return total += getRangedDouble

The options you want to feed are scanner, prompt, low and high limits.

( file, "Specify the price between:", 0.50, 9.99);



In getRangedDouble

you want to receive user input while the answer is invalid. So you were right, just keep reading until the next good hint comes along.

After that, get and check their price until you get your desired price range.

retVal < 10 && retVal > 0.5

      

When it does, it really is. Set to true and return retVal. To format the total, all you have to do is use DecimalFormat. This line creates a decimal formate with #.##

2 decimal words precision.

DecimalFormat df = new DecimalFormat ("#. ##");

then you can call df.format( total )

to format your total when printing. In the meantime, there is no need to worry about it. ”

+1


source


I only see one use of your method getYNConfirm

(which is weird), but it has a rather subtle logical error.

Note:

while(!done)

      

If done

- true

, then the above expression reads:

while(false)

      

... which indicates that this loop will never run .

From what you've shown us so far, the solution is as simple as converting the original state done

to false

:

boolean done = false;

      

As an aside, generally, you want to return boxed types for primitives when you absolutely must. In this case, I don't see in you a return value, Boolean

not Boolean

.

0


source







All Articles