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:
- 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.
Aucun commentaire:
Enregistrer un commentaire