Solved

ArrayList and A Shopping Cart

Posted on 2011-02-14
31
2,358 Views
Last Modified: 2012-05-11
Hi,

I have an assignment related to this topic:
http://www.experts-exchange.com/Programming/Languages/Java/Q_26787791.html

What I am working on currently is the "upgrade" to the first.

It involves ArrayLists.  It's not that I am having problems populating one, it's that I have to do stuff with pieces of the string going into the list itself.


Here's the task.  Use an ArrayList as a shopping cart to hold the cart objects .  The ArrayList has to be fed from an input file.  
-<Item code> space <Item price> space <Item name> ( you may use other delimeters instead of space)
-After reading a line from the input file create an Item object using the data read from the file. The default quantity value of each item is 1.
-Write a class SalesItem that extends Item

1. Data fields(instance variables): This class has data fields for the discount percentages ( best if they are declared as final
static)and a data field to indicate the discounted rate of the SalesItem object.

2.Constructor: The SalesItem class should have a 4 parameter constructor to assign values to the instance variables.
Remember to use the parent class' method for setting the data.

3. Methods: The SalesItem class should have a method to set the discount rate for an item. Any item, which starts with the code A, B, or C is discounted. Assume that A items have 20% discount rate, B items have 25% discount rate and the C items have 10% discount rate. Any item that is on sale should also be indicated in the final bill as "Discount" along with the percentage amount. Hint:Override the toString method of the parent class. Feel free to add more methods to the SalesItem class according to your algorithm.  Since the cart object will hold a combination of Item and SalesItem objects, you will have to revise it as well.
 
Finally, write a program that simulates shopping during sales( e.g. SalesShopping.java). The program should have a loop that continues as long as the user wants to shop. Each time in the loop, display the list of Items that can be shopped by the user (item code, name and unit price) and ask the user to type in the selected item code. If the code is entered correctly( check with the shoppable item list objects), ask the user to type in the quantity of the item the customer wants. Create an Item object by using input data and the ArrayList ( shoppable list of Item objects )and add it to the cart. The ArrayList object should be used to fill in the name and the price of the item that the user has requested.
  Once the shopping is completed, the application should prepare and print a summary report to the customer (on the screen
and to an output file) summarizing the list of objects in the shopping cart ( Please note that SalesItem objects should "Discount" along with the percentage amount.) . Finally, print a message such as "Please pay ..." with the total price of the items in the cart.

Sample Output:

List of Items:
A1234 Notebook 1.0
B1122 Book 7.99
C5678 Pencil 0.69
D4532 Magazine 3.33
Enter the code of the item to be purchased:
A1234
Enter the quantity of A1234 that you wish to purchase:
3

Do you want to continue (y/n)?
y
List of Items:
A1234 Notebook 1.0
B1122 Book 7.99
C5678 Pencil 0.69
D4532 Magazine 3.33
Enter the code of the item to be purchased:
D5432
Please reenter the code of the item to be purchased:
D4532
Enter the quantity of D4532 that you wish to purchase:
2
Do you want to continue (y/n)?
n
---------------------------------------------------------------------------
Shopping Cart
ItemCode ItemName UnitPrice Quantity Total
---------------------------------------------------------------------------
A1234 Notebook $0.80 3 $2.40 Discount 20.0%
D4532 Magazine $3.33 2 $6.66
---------------------------------------------------------------------------
Total Price: $9.06
Please pay: $9.06
----------------------------------------------------------------------------------------

Here is as far as I have gotten:

ShoppingCart.java

 SalesShopping.java

 SalesItem.java

 Item.java

I am able to get objects into the arraylist and display them, it's the manipulation of the stuff within that giving me trouble.  I am also fairly certain that I am (as ever) doing something the hard way.  I would appreciate any help I can get.

Thanks
0
Comment
Question by:g_currier
  • 19
  • 12
31 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 34893522
Why would we notreturn to that previous one, which worked for the most part (actually I think it worked
for all options) and then incrementally change what we need to change
 Let's return to the code which I sent you in ID 34767922 and let's inbcremenetally
modify what we need to modiify.

That is how you do it - you make one small change - and then run and check - if it didn't break
then you make another change and then again check.
This is much more effective, than to re-write a whole lot and discover that it is broken
at all possible points.
So this is my suggestion - start from the code I sent you in that old message -
and formulate what you want to change first. If you want I cabn help you.
Then we'll make sure that it works with this one change, and formulate
next one thing - and so on.
The principle should be that at every possible moment you should have fully functional and debugged program,
and then you make just one step - and not move forward  until you have
fully working new variant.
 It seems tedious - in fact it is much more effective than to do many changes simultaneously and then
trying to find all places where it is broken.

So, my suggestion - look at that old code, and let me know what is the first thing
we want to change starting from that code.




0
 
LVL 47

Expert Comment

by:for_yan
ID: 34893529
I tried and compiled your latest variant - an it immediately reports errors for all operations.
That is the reason for my suggestion above.
0
 

Author Comment

by:g_currier
ID: 34895310
OK..I'll start by changing the shoppingcart class (addToCart ()) to an arrayList and leave the rest as is then see if I can get it working.  I'll post results shortly.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34895367
No, I definitely tested the codes I sent you - just start from them - that was even
before you added all these asterisks. Please, try those - they didn't produce errors,
at least in straightforward cases - maybe only in some
special combination of cases. This code which i tried
today produces error just on the first selection of say option 1.

If I have time I'll also return to my old code tomorrow and check.
And then it should be extended stepwise - after each step testing
if it still works. Sometimes even adding asterisks mistakes can be introduced,
therefore even after cosmetic changes - first thing is to check - and only
then to go forward. It only seems that that would be slower.
In fact such system would eventually pay off.

0
 

Author Comment

by:g_currier
ID: 34895371
OK...I'll use what you sent and work from there.  
0
 

Author Comment

by:g_currier
ID: 34895546
OK.  the prior unaltered GoShopping and Item classes with the changes I made to Shopping Cart.

It runs but does not add anything to the ArrayList, saying that the list is already full.


GoShopping.java

Item.java

ShoppingCart.java
0
 

Author Comment

by:g_currier
ID: 34895585
removed lines 27-29

if (currentNumberOfItems >= cart.size()) {
            return false;
        }

to allow the insertion of an Item obj.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34895602
OK. I hope I'll have time tomorrow (it is already 3 am here now) I'll check again and let you know what I find.
0
 

Author Comment

by:g_currier
ID: 34895608
I am in Germany so I'll be finishing my day when you start yours...I'll keep working on the ShoppingCart class.
Thanks
0
 

Author Comment

by:g_currier
ID: 34900628
I tried to figure out how to get the array list back to an array (so i could use the parts - price and quantity - in math manipulation).  I was unsuccessful, though I think I got close.

GoShopping.java
 
package TestPackage;

import java.util.*;
import java.io.*;
import javax.swing.*;
//import java.lang.*;

public class GoShopping {

    public static void main(String[] args) throws Exception {

        // Item item = new Item();
        ShoppingCart cart = new ShoppingCart();
        Scanner input = null;
        final String INPUT_FILE = "StoreItemsList.txt";
        File inputFile = new File(INPUT_FILE);

        if (!inputFile.exists()) {
            JOptionPane.showMessageDialog(null,
                    "File '" + INPUT_FILE + "' not found. \nClick OK to end program.",
                    "File Not Found Error", JOptionPane.ERROR_MESSAGE);
            System.out.println("File '" + INPUT_FILE + "' not found.");
            System.exit(0);
        }
        Scanner scanner = new Scanner(System.in);

        // Scanner input = new Scanner(inputFile).useDelimiter("\\-");

        System.out.println("Hello! Please choose an option from the menu.\n");
        boolean isFull = false;
        int choice = 5;
        int count = 0;

        String answer = "";

        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    input = new Scanner(inputFile).useDelimiter("-");
                    while (input.hasNextLine() && !isFull) {
                        String strQuantity = "1";
                        String line = input.nextLine();
                        String[] lineItem = line.split("-");
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];

                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[2] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");
                        answer = scanner.next();
                        if (answer.equalsIgnoreCase("Y")) {
                            //String strQuant = lineItem[2].trim();
                            //String strPrice = lineItem[3].trim();
                            //strQuantity = strQuantity;
                            //strPrice = strPrice.trim();
                            int itemQuantity = Integer.parseInt(strQuantity);
                            double itemPrice = Double.parseDouble(strPrice);
                            Item item = new Item();
                            item.setItemCode(itemCode);
                            item.setItemName(itemName);
                            //temporary - just to put a number in the quant position until quantity mulitplier is created
                            item.setItemQuant(itemQuantity);
                            item.setItemPrice(itemPrice);
                            
                            if (cart.addToCart(item)) {
                                System.out.print("Item added to your cart.\n");
                                //cart.getListToArray();
                            } 
                        } else {
                            System.out.print("No items added");


                        }
                        // break;
                    }
                    input.close();
                    break;
                case 2:
                    System.out.println(cart.toString());
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //cart.getListToArray();
                    //System.out.println("You have total of " + cart.getTotalNumber() + " purchases. ");
                    //System.out.println("Your total is : $" + cart.getTotalPrice());
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(0);
            }
        }
    }

    public static void displayMenu() {
        System.out.println("\n-----------------------------------------");
        System.out.println("Select an Option and enter your choice.");
        System.out.println("1) Add items to your cart.");
        System.out.println("2) Display the items in your cart and the\n"
                + "   running total.");
        System.out.println("3) Empty your cart.");
        System.out.println("4) Checkout.");
        System.out.println("5) Quit");
        System.out.println("-----------------------------------------");
        System.out.print("Enter a number (1 through 5) as your choice: ");
    }
}

Open in new window


ShoppingCart.java
 
package TestPackage;

import java.util.ArrayList;

public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    //private int capacity;
    private int currentNumberOfItems;
    //int usedCapacity;
    double totalPrice;

    public ShoppingCart() {
        cart = new ArrayList();
        MyCart = "My Selected Items";
        totalPrice = 0.00;
        currentNumberOfItems = 0;

    }

    public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            return false;
        }
        currentNumberOfItems++;
        return true;
    }
    public void EmptyCart() {
        currentNumberOfItems = 0;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        //Item item = new Item();
        this.totalPrice = totalPrice;
        return totalPrice;
    }

    //thought that trying to cast the ArrayList of objects to an array would help
    //accomplish parsing the pieces into something usable (i.e. prices and quantities) for
    //math manipulation
//    public Object[] getListToArray() {
//        int i = 0;
//        Object itemList[] = new Object[cart.size()];
//        itemList = (Object[]) cart.toArray(itemList);
//       for (i=0;i<=cart.size();i++){
//           System.out.print(itemList[i]);
//       }
//        return itemList[4];
//    }


    public double getTotalPrice(){
       double sum = 0.00;
       int i = 0;
       return sum;
    }
//    public int getTotalNumber(){
//        int totNum = 0;
//         for(int j=0; j<currentNumberOfItems; j++){
//            totNum += cart[j].getItemQuant();
//
//        }
//
//        return totNum;
//    }
    public int cartSize(){
        int cartSize = cart.size();
        return cartSize;
    }

    @Override
    public String toString() {
        String s = "";
        for (int j = 0; j < cart.size(); j++) {
            s += cart.get(j);
        }
        System.out.println("Code\t   Price\t Item\t\t\t\t\tQuantity");
        return s;
    }
}

Open in new window


I left the Item.java class alone for now (until I have to develop the Sale Item class, I'll leave it be).

For now, the list gets fed into the cart successfully.

Still need to display the list after adding an item and allow specific selection of items from that list as well as increase quantity amount if the same item is selected more than once.  Working on it...
0
 

Author Comment

by:g_currier
ID: 34900775
forgot to include the text file

Currently working on the toString method and/or the listToArray method.
StoreItemsList.txt
0
 

Author Comment

by:g_currier
ID: 34900816
And I did change the Item class: I changed the order of parameters in the Item constructor (to keep everything in the same order as the input file.


package TestPackage;

public class Item {
    private String itemName;
    private String itemCode;
    private int itemQuant;
    private double itemPrice;
    private int itemCapacity;



    //default constructor
    public Item(){
        itemName = null;
        itemQuant = 0;
        itemPrice = 0.00;
        itemCode = null;
        itemCapacity = 0;

    }
    //contructor with parameters
    public Item(String code,double price,String name,int quantity ){
        this.itemCode = code;
        this.itemPrice = price;
        this.itemName = name;
        this.itemQuant = quantity;
        
    }
    public Item(int itemCapacity){
        this.itemCapacity = itemCapacity;
    }

    //accessor methods
    public String getItemName(){
        return itemName;
    }

    public int getItemQuant(){
        return itemQuant;
    }

    public double getItemPrice(){
        return itemPrice;
    }

    public String getItemCode(){
        return itemCode;
    }

    public int getSize(){
        return itemCapacity;
    }
    //mutator methods
    public void setItemName(String name){
        this.itemName = name;
    }

    public void setItemQuant(int quant){
        this.itemQuant = quant;
    }

    public void setItemPrice(double price){
        this.itemPrice = price;
    }

    public void setItemCode(String code){
        this.itemCode = code;
    }

    //other methods
    @Override
    public String toString(){
        return
                getItemCode()+"\t"+
                getItemPrice()+"\t"+
                getItemName()+"\t"+
                getItemQuant()+"\n";
                

    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901069
this old stuff wors for me in all cases which I checked.
I suggest - look at it and say waht new thing we want to add.
If you want some variant when it does not work - also tell me.


GoShopping.java
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901072
Sorry, I'll now post the rest of them
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901097
These are the rest of them
ShoppingCart.java
Item.java
itemList.txt
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:g_currier
ID: 34901116
Well, for starters, I have to meet the requirements of the assignment.  The way it was done before was fine, but this one is a bit more specific and restrictive.
The goal I ahve to meet are stated in the first post, as well as how it has to "look" (I also get graded on "visual appeal" so there's that I have to consider as well.

What I need for just functionality at the moment is the ability to get the total cost of the cart.
After that I need the ability to update the quatity count of a cart item and reflect that in the price (hence the extra SalesItem class).
For me that's plenty at the moment.
0
 

Author Comment

by:g_currier
ID: 34901129
I had all the ones you sent saved and that's what I started with following the step-wise refinement idea.  what I posted recently was the result.
0
 

Author Comment

by:g_currier
ID: 34901151
oh yeah, casting the arraylist to an array (I figured out after looking at it, does absolutley nothing...each item is still one array item (i.e. the whole line as opposed to each input separated so that I can work with it)  I also tried reading the toString method into a scanner using a delimiter...that didn't work either...
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901183
But this one calculates the total cost of the cart when you dio checkout.
If you want to add asterisks - that is also fine - but just do only this - be
autify it - and test it - make sure you didn't spoil the substance then go forward.

You want arraylist instead of array in the cart - also fine - in fact
it is a much better idea, you don't need to limit capacity and in genral I prefer
ArryLists to arrays - so we can chnage just that - it will be limited to the
internals of the cart - and then again run through all options -  make sure it works.
This way it would be much easier and it will never be in broken state.

I suggest add only asterisks test it - post it back - I can then change
to arraylist.
0
 

Author Comment

by:g_currier
ID: 34901340
use this ShoppingCart and input file (change the name in the GoShopping class)
I changed it to an arraylist earlier

It reads the input file into the list, i'm just at a loss as to how to get the info from it to determine price totals, quantities etc...
please review the code (it's the same as you gave - just modified enough to accomodate the arrayList)

GoShopping.java
 
/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 *
 */
package P2;

import java.util.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class GoShopping {

    public static void main(String[] args) throws Exception {

       // Item item = new Item();
        ShoppingCart cart = new ShoppingCart();
          Scanner input = null;
        final String INPUT_FILE = "StoreItemsList.txt";
        File inputFile = new File(INPUT_FILE);

        if (!inputFile.exists()) {
            JOptionPane.showMessageDialog(null,
                    "File '" + INPUT_FILE + "' not found. \nClick OK to end program.",
                    "File Not Found Error", JOptionPane.ERROR_MESSAGE);
            System.out.println("File '" + INPUT_FILE + "' not found.");
            System.exit(0);
        }
        Scanner scanner = new Scanner(System.in);

       // Scanner input = new Scanner(inputFile).useDelimiter("\\-");

        System.out.println("Hello! Please choose an option from the menu.\n");
        boolean isFull = false;
        int choice = 5;
        int count = 0;
        String answer = "";

        while (choice > 0) {
            displayMenu();
            choice = scanner.nextInt();

            switch (choice) {
                case 1:
                      input = new Scanner(inputFile).useDelimiter("\\-");
                    while (input.hasNextLine() && !isFull) {

                        String line = input.nextLine();
                        //String word = input.next();
                        String[] lineItem = line.split("\\-");
                        //formatted the input file, don't need trim function
                        String itemCode = lineItem[0];
                        String strPrice = lineItem[1];
                        String itemName = lineItem[2];

                        System.out.print("Add item code " + lineItem[0] + ",\"" + lineItem[1] + "\"to your cart?\n"
                                + "Type \"Y\" for Yes or \"N\" for No.\n");

                        answer = scanner.next();
                        if (answer.equalsIgnoreCase("Y")) {
                            int itemQuantity = 1;
                            double itemPrice = Double.parseDouble(strPrice);
                                  Item item = new Item();
                            item.setItemCode(itemCode);
                            item.setItemPrice(itemPrice);
                            item.setItemName(itemName);
                            item.setItemQuant(itemQuantity);
                            
                            if(cart.addToCart(item)){
                            System.out.print("Item added to your cart.\n\n");
                            } else
                            {
                                  System.out.print("Too many items in your cart. Go to checkout or empty cart\n\n");
                            }
                        }
                        else{
                            System.out.print("No items added");


                        }
                       // break;
                    }
                    input.close();
                    break;
                case 2:
                   System.out.println(cart.toString());
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //don't know how to get these using an arraylist
//                    System.out.println("You have total of " + cart.getTotalNumber() + " purchases. ");
//                    System.out.println("Your total is : $" + cart.getTotalPrice());
                    break;
                case 5:
                    input.close();
                    System.out.println("Thank you! Come again!");
                    System.exit(1);
            }
        }
    }

    public static void displayMenu() {
        System.out.println("\n-----------------------------------------");
        System.out.println("Select an Option and enter your choice.");
        System.out.println("1) Add items to your cart.");
        System.out.println("2) Display the items in your cart and the\n"
                          +"   running total.");
        System.out.println("3) Empty your cart.");
        System.out.println("4) Checkout.");
        System.out.println("5) Quit");
        System.out.println("-----------------------------------------");
        System.out.print("Enter a number (1 through 5) as your choice: ");
    }
}

Open in new window


ShoppingCart.java
 
package P2;

import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    //private int capacity;
    private int currentNumberOfItems;
    //int usedCapacity;
    double totalPrice;

    public ShoppingCart() {
        cart = new ArrayList();
        MyCart = "My Selected Items";
        totalPrice = 0.00;
        currentNumberOfItems = 0;

    }

    public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            return false;
        }
        currentNumberOfItems++;
        return true;
    }
    public void EmptyCart() {
        currentNumberOfItems = 0;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        //Item item = new Item();
        this.totalPrice = totalPrice;
        return totalPrice;
    }

//    public double getTotalPrice(){
//        double sum = 0.0;
//        for(int j=0; j<currentNumberOfItems; j++){
//            sum += cart[j].getItemPrice()*cart[j].getItemQuant();
//
//        }
//        return sum;
//    }
//
//    public int getTotalNumber(){
//        int totNum = 0;
//         for(int j=0; j<currentNumberOfItems; j++){
//            totNum += cart[j].getItemQuant();
//
//        }
//
//        return totNum;
//    }


    @Override
    public String toString(){
        String s =  "Item\t\t\tCode\t\tQuantity\t\tPrice"+
                "\n";
          for(int j=0; j<currentNumberOfItems; j++){
              s += cart.get(j);
          }
        return  s;
    }
}

Open in new window


Item.java
 
package P2;

public class Item {
    private String itemName;
    private String itemCode;
    private int itemQuant;
    private double itemPrice;
    private int itemCapacity;



    //default constructor
    public Item(){
        itemName = null;
        itemQuant = 0;
        itemPrice = 0.00;
        itemCode = null;
        itemCapacity = 0;

    }
    //contructor with parameters
    public Item(String code,double price,String name,int quantity ){
        this.itemCode = code;
        this.itemPrice = price;
        this.itemName = name;
        this.itemQuant = quantity;

    }
    public Item(int itemCapacity){
        this.itemCapacity = itemCapacity;
    }

    //accessor methods
    public String getItemName(){
        return itemName;
    }

    public int getItemQuant(){
        return itemQuant;
    }

    public double getItemPrice(){
        return itemPrice;
    }

    public String getItemCode(){
        return itemCode;
    }

    public int getSize(){
        return itemCapacity;
    }
    //mutator methods
    public void setItemName(String name){
        this.itemName = name;
    }

    public void setItemQuant(int quant){
        this.itemQuant = quant;
    }

    public void setItemPrice(double price){
        this.itemPrice = price;
    }

    public void setItemCode(String code){
        this.itemCode = code;
    }

    //other methods
    @Override
    public String toString(){
        return
                getItemCode()+"\t"+
                getItemPrice()+"\t"+
                getItemName()+"\t"+
                getItemQuant()+"\n";


    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901388
OK, I'll look at price and totals  calculation
0
 

Author Comment

by:g_currier
ID: 34901757
I'm going to take a wild leap and say that this won't possibly work (either using b.toString() or c.toString());
public static void getPrice(){
        String price = null;
        Item b = new Item();
        ShoppingCart c = new ShoppingCart();
        Scanner input = new Scanner(c.toString()).useDelimiter("\\t");
        while (input.hasNextLine()){
            String line = input.next();
            String[] thisPrice = line.split("\\t", 1);
            price = thisPrice[0];
        }
        System.out.print(price);
    }

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 34901947

You have a number of mistakes in the ShoppingCart - as soon as you add new
item you need to update your current totals, so that they  will always be
uptodate (see below)

then in EmptyCart you want to zero both currentNumberOfItems
and total Price.

  public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            return false;
        }
      //  currentNumberOfItems++;

          currentNumberOfItems += newItem.getItemQuant();
          totalPrice +=  newItem.getItemQuant()*newItem.getItemPrice();
        return true;
    }

And  would you need this method for reading price separately?
You get from your cart to individual items, and then
from item get Price - why would you need to read the
price back from the string? You already parsed the file once - there should be no need
to get it again from the string




0
 

Author Comment

by:g_currier
ID: 34901966
That's the problem...how?  I know just enough to do it wrong.  There is something I am missing from getting the price back (I've been at it all day).  Can you show me?
0
 

Author Comment

by:g_currier
ID: 34901996
Like this?  
 
case 2:
                    System.out.println(cart.totalPrice);
                    break;

Open in new window

0
 

Author Comment

by:g_currier
ID: 34902037
OK, that worked.  I still have much left to accomplish with this.  It seems fair that I accept the solution and award points.  However, If I open another thread for the next part will continue to assist me please?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34902042
You saw the addNewItem() method where you add totals
If you keep adding total price with each new item and total quanity
with each new item, if you zero them when doing Empty() method, then your
totals will be sitting in the ShoppingCart class all the time beiing uptodate.
The you just have methods


public double getTotalPrice() {
return totalPrice;

}
public int getTotalNumber() {
return currentNumberOfItems;
}

and you jsut print:

System.out.println("Total Price: " + c.getTotalPrice());
System.out.println("Ttal number: " + c.getTotalNumber());


then you final method will just return these numbers and you don't need to worry - of course you
should not parse it back from cart.toString();
0
 

Author Closing Comment

by:g_currier
ID: 34902072
Got it.  I can return the total price of the cart...pretty comes later.  Onwards then
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34902082

I will assist you but I urge you to follow reasonable way.
Your code which you posted today still is not like the one I posted you - the
initial part when we did the parsing in the file and reading
was working in my code, but does not work now.
before you change anything - test all options and debug - it should be in working condition
at every moment - only in this way we could move forward.
So try to fix yourslef what is not working now without any "improvemnets"
If some issue in particular you don;'t know how to fix - let me know I'll help
you - but don't "improve" until everyrthing is working at the current stage as it should.


0
 

Author Comment

by:g_currier
ID: 34902107
It may be that you are using the wrong input file.  I had to change it to match the required format.  additionally, I altered the parameters in the item constructor to match the order of input.  case all the cases work with the exception of the additonal functionality I am required to have.  Other than that, I have not altered anything else as per your advice.

Here is the new input file:
 StoreItemsList.txt
0
 

Author Comment

by:g_currier
ID: 34902118
new thread is 26824094
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now