1

I'm trying to design a shopping cart that reads dollar amounts and then prints those values back. My while loop, however, won't terminate and my arraylist is storing erroneous values.

 /**
 * This method is the shopping cart
 */
public static void shoppingCart()
{
    // create scanner objects
    Scanner textReader = new Scanner(System.in);
    Scanner numberReader = new Scanner(System.in);
    // declare variables
    int counter = 0;
    // create arraylist object
    ArrayList<Double> cartItems = new ArrayList<Double>();
    // create decimal format object
    DecimalFormat dollarformatter = new DecimalFormat("$#0.00");
    // print out the first prompt
    System.out.print("Would you like to input item/s - y/n: ");
    String response = textReader.nextLine();
    System.out.println();
    // create while loop to restrict responses to single characters
    while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
    {
        System.out.print("Sorry - we need a y/n: ");
        response = textReader.nextLine();
        System.out.println();
    }
    // create while loop for positive response
    while ((response.equalsIgnoreCase("y")))
    {
        System.out.print("Please enter an item price, or -1 to exit: $");
        double values = numberReader.nextDouble();
        cartItems.add(values);
        if ((values > (-1)))
        {
            System.out.print("Please enter another item price, or -1 to exit: $");
            values = numberReader.nextDouble();
            cartItems.add(values);
        }
        else if ((values <= (-1)))
        {
            System.out.println();
            System.out.println("********** Here are your items **********");
            System.out.println();
            for (counter = 0; counter < cartItems.size(); counter++)
            {
                System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter));
            }
        }
    }
    System.out.println();
    System.out.println("********** Thank you for using the shopping cart **********");
}

The results should look like this:

Correct output

But this is my output:

my output

  • The while loop won't terminate and goes back to the first prompt: "please enter an item price, or -1 to exit:"
  • The program keeps counting the "-1" as part of the arraylist. The "-1" value is supposed to act as a "no" and terminate the addition of more elements to the arrayList but in my code, it gets absorbed into the arrayList. I've tried turning the "-1" into a string to get the program to "ignore" it but it doesn't work.
  • After the program lists the final item (in my output it is #3), it is supposed to ask if the user wants to delete an item. I have not gotten this far as I am quite stumped as to why my while loop refuses to terminate and why "-1" keeps getting included in my arraylist. Any help with this is greatly appreciated it as I've been mulling over this for a day now with no luck.

Updated code; loop termination issue appears to be solved but the "-1" isn't triggering an exit and it's still getting added to the arrayList.

while ((response.equalsIgnoreCase("y"))) {
    System.out.print("Please enter an item price, or -1 to exit: $");
    double values = numberReader.nextDouble();
    cartItems.add(values);
    while ((values != (-1))) {
    System.out.print("Please enter another item price, or -1 to exit: $");
    values = numberReader.nextDouble();
    cartItems.add(values);
    }
    System.out.println();
    System.out.println("********** Here are your items **********");
    System.out.println();
    for (counter = 0; counter < cartItems.size(); counter++) {
    System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter));
    }
    break;
}
3
  • 1
    Your else if statement is still inside the while loop so the prompt will be printed again. Maybe you should consider putting in a break statement? Also you add the value to the cart before your if and else statements, so it will still add -1. Commented Dec 2, 2017 at 4:35
  • Would you be able to explain why it won't read "-1" as "exit"? Even when I type in "-1", the code keeps running. Commented Dec 2, 2017 at 4:40
  • A while loop keeps repeating when the condition is true. The if else statement gets entered, but it goes back to the top of the while loop. Commented Dec 2, 2017 at 4:42

2 Answers 2

1

Problem 1: cartItems.add(values) happens before the if statement, meaning -1 still gets added to the cart. In other words, you are adding values to the cart BEFORE you even test if it's below zero.

Problem 2: your else if executes, but since it's in a while loop and your response hasn't changed, it prompts the user again since the while loop condition is still true. I suggest putting a break statement at the end of the else if statement. But my code removes the need for that.

Here's what I would do:

if((response.equalsIgnoreCase("y")))
{
    System.out.print("Please enter an item price, or -1 to exit: $");
    double values = numberReader.nextDouble();
    while ((values > (-1)))
    {
        cartItems.add(values);
        System.out.print("Please enter another item price, or -1 to exit: $");
        values = numberReader.nextDouble(); 
    }
 }
 System.out.println();
 System.out.println("********** Here are your items **********");
 System.out.println();
 for (counter = 0; counter < cartItems.size(); counter++){
      System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter));
 }
 System.out.println();
 System.out.println("********** Thank you for using the shopping cart **********");

Basically what I did was realize that all you need was a way to have a while loop such that you wouldn't have to prematurely add to your cart before you knew it was below 0 as you did in your earlier code. I suggest looking into a fence post problem. A fence post is in the form |-|-| etc. So the fence post was your prompt and the wires was adding the values. Thus, my way is better because I switched the ordering. It's as simple as that.

Sign up to request clarification or add additional context in comments.

9 Comments

I think I fixed the the loop termination issue but the -1 is still getting added.
Did you put the cartItems.add(values) inside the if statement and remove it from before the if statement?
I actually removed the if/else statement entirely. Instead, I used a while statement. I updated the code in my original post above. Would you recommend I use an if/else statement? I thought perhaps a while statement might clarify things.
I thought the earlier code was fine. You have the add(values) twice still. Remove the one before the if statement in your old code. In your new code remove it for the nested while loop.
Yeah no problem, I'm glad it helped. Maybe your class hasn't gotten to it yet, I encounter fence post problems almost every week. upvotes are appreciated :)
|
0

Keep in mind that you have your for loop inside multiple different conditions. It will keep running until that while loop is done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.