Solved

updating quantity with multiple identical newItems

Posted on 2011-02-15
19
361 Views
Last Modified: 2012-05-11
I need now to update the quantity if the same item is selected to go into the cart.
0
Comment
Question by:g_currier
  • 10
  • 9
19 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
OK. That actually needs just modification of addToCart method
You go through your arraylist check your code and if the code of new item
is the same as the item existing in the list you just modify quantity of that
item and replace  it in your array list
rathere than adding a new item. try to do it - i'll chek.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Howvere, I suggest that you first check the first part odf just reading the file.
I don't think it worked for me with your code - and it is crucial in order to
do any further testing.

In the previous variant it did work. You want to add the question about quantity rather than reading quatity from file?
Fine, but concentrate on that and make sure it reads it all correctly.

also if and when you will want my help - post also your input file - I feel
you changed format of that one in the meantime also.
0
 

Author Comment

by:g_currier
Comment Utility
Yes, I changed the input file (I posted it in the last thread).  I was required to according to instructions.  In this I cannot use an item quantity (in the input file).  It has to be generated dynamically.  To accomplish this using the item constructor I also had to change case 1 a little (ArrayIndexOutOfBounds exception?)
her is the change in the GoShopping class:
 
/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 *
 */

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[2] + "\"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:
                    cart.toString();
                    System.out.println("Your current bill is $"+cart.totalPrice);
                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file
                    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


and here is the new input file:

 StoreItemsList.txt

to be sure, here are the other two:
 ShoppingCart.java
 Item.java

While I'm at it, this will explain everything better than I can:

 lau.pdf
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
OK, so try to fix this array out of bounds - do you use soem IDE?
If so, it should show you exact line wher it happens. Look at this line and
then add suitable printout just before that line of parameters involved.
That will give you a clue.
try to do it yourself. If you cannot I'll ok at that also.


 
0
 

Author Comment

by:g_currier
Comment Utility
It's all fixed as per the changes in the code I posted.  I am now trying to figure out the comparison of items for quantity update.
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
Comment Utility
OK. Comparison of newItem o existing items should go something like that:

String code = newItem.getItemCode();
for(int j=0; j<cart.size(); j++){
Item it = (Item) cart.get(j);
String curCode = it.getItemCode();
if(curCode.equals(code)){

it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
cart.replace(it,j); //check if ArrayList.replace method has this order of arguments

}else
cart.add(newItem);
}

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Maybe you actually don't even need replace, but I think it is safer; no, probably you will still need to replace
after you modify the item, to ensure that mnow modified item
is in the ArrayList.
0
 

Author Comment

by:g_currier
Comment Utility
So I don't need the equals() method i just created?
import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    private String code;
    private String name;
    
    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;
        }
        this.code = newItem.getItemCode();
        this.name = newItem.getItemName();
        
        currentNumberOfItems = newItem.getItemQuant();
        totalPrice += newItem.getItemQuant()*newItem.getItemPrice();
        return true;
    }
    public boolean inList(Item newItem){
        return cart.contains(newItem);
    }
    public boolean equals (Item a){
        if((code.equals(a.getItemCode()))&&(name.equals(a.getItemName())))
            return true;
        else
            return false;
    }
    public void EmptyCart() {
        currentNumberOfItems = 0;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        this.totalPrice = totalPrice;
        return totalPrice;
    }


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

Open in new window

0
 

Author Comment

by:g_currier
Comment Utility
cart.set(j,it);
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Yes, cart.set(j,it) should be fine.

No, I don't think you need equals method, it is a little bit of overkill
in this case.
I think comparing codes as strings is probably enough.
In more real life situation, name can indeed  be not exactly
the same, but code should be unique id of the type of product,
 so once code is the same
you can safely assume that it is the same item.
Of course no one should blame you too
if you implement and use equals method for Item,
especially in exercise environment.

0
 

Author Comment

by:g_currier
Comment Utility
Added the code into the addToCart() mehtod and got interesting results.  not sure why the resutls are as such but here they are:

I added the first item twice and the second itm once with this output:

-----------------------------------------
Select an Option and enter your choice.
1) Add items to your cart.
2) Display the items in your cart and the
   running total.
3) Empty your cart.
4) Checkout.
5) Quit
-----------------------------------------
Enter a number (1 through 5) as your choice: 2
Code           Price         Item                                           Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSG        429.99        Western Digital Caviar Green 3TB HDD        4
D1X2FSG        429.99        Western Digital Caviar Green 3TB HDD        4
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        8
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        8
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        8

Your current bill is $5619.860000000001

I really need to sleep - it's almost 2 am.  I'll be back around 9 or 10 pm your time...

code usage on ShoppingCart:
 
import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    private String code;
    private String name;

    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;
        }
        code = newItem.getItemCode();
        for (int j = 0; j < cart.size(); j++) {
            Item it = (Item) cart.get(j);
            String curCode = it.getItemCode();
            if (curCode.equals(code)) {
                it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                cart.set(j,it); //check if ArrayList.replace method has this order of arguments
            } else {
                cart.add(newItem);
            }
        }
        currentNumberOfItems = newItem.getItemQuant();
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
        return true;
    }

    public void EmptyCart() {
        currentNumberOfItems = 0;
        totalPrice = 0.00;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        this.totalPrice = totalPrice;
        return totalPrice;
    }


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

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility
That is because you (maybe among other things)  didn't remove the piece of
code which used to be adding item unconditionally in the beginning
of addToCart method :

if (!cart.add(newItem)) {
            return false;
        }

As we are adding item below  we should not add it one more time above.
0
 

Author Comment

by:g_currier
Comment Utility
of course...see that now after some sleep.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

Check how it works when you fix this issue and let me know. If there is still some issue we'll look at it tomorrow (if we speak in the pacific time)
0
 

Author Comment

by:g_currier
Comment Utility
This, of course, adds each item in turn, regardless whether it matches any item already in:
 
public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            return false;
        }
        currentNumberOfItems = newItem.getItemQuant();//set new value
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();//math for price
        return true;
    }

Open in new window

with the following result:
-----------------------------------------
Select an Option and enter your choice.
1) Add items to your cart.
2) Display the items in your cart and the
   running total.
3) Empty your cart.
4) Checkout.
5) Quit
-----------------------------------------
Enter a number (1 through 5) as your choice: 2
Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        1
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        1

Your current bill is $779.98


This way :

 
public boolean addToCart(Item newItem) {
        String code = newItem.getItemCode();
        for (int j = 0; j < cart.size(); j++) {
            Item it = (Item) cart.get(j);
            String curCode = it.getItemCode();
            if (curCode.equals(code)) {
                it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                cart.set(j, it);
            } else {
                cart.add(newItem);
            }
        }
        currentNumberOfItems = newItem.getItemQuant();//set new value
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();//math for price
        return true;
    }

Open in new window


returns this:

Enter a number (1 through 5) as your choice: 2
Code           Price         Item                                        Quantity

Your current bill is $779.98

So I experimented - and in each test I added the first input item twice and nothing else:
 
public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            return false;
        }
        String code = newItem.getItemCode();
        for (int j = 0; j < cart.size(); j++) {
            Item it = (Item) cart.get(j);
            String curCode = it.getItemCode();
            if (curCode.equals(code)) {
                it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                cart.set(j, it);
            } else {
                //cart.add(newItem);
                return false;
            }
        }
        currentNumberOfItems = newItem.getItemQuant();//set new value
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();//math for price
        return true;
    }

Open in new window


this is the return from attempt 1:

Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        2

Your current bill is $1559.96

Experiment 2:
 
public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {
            //return false;

            String code = newItem.getItemCode();
            for (int j = 0; j < cart.size(); j++) {
                Item it = (Item) cart.get(j);
                String curCode = it.getItemCode();
                if (curCode.equals(code)) {
                    it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                    cart.set(j, it);
                } else {
                    //cart.add(newItem);
                    return false;
                }
            }
        }
        currentNumberOfItems = newItem.getItemQuant();//set new value
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();//math for price
        return true;
    }

Open in new window

Result 2:

Code             Price            Item                                                           Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        1
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        1

Your current bill is $779.98

Experiment 3:
 
public boolean addToCart(Item newItem) {
        if (cart.add(newItem)) {
            //return false;
            String code = newItem.getItemCode();
            for (int j = 0; j < cart.size(); j++) {
                Item it = (Item) cart.get(j);
                String curCode = it.getItemCode();
                if (curCode.equals(code)) {
                    it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                    cart.set(j, it);
                }
            }
        } else {
            //cart.add(newItem);
            return false;
        }
        currentNumberOfItems = newItem.getItemQuant();//set new value
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();//math for price
        return true;
    }

Open in new window

Result 3:
Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        2

Your current bill is $1559.96

Experiment 4:
Note that I added a line to the case to show the current number of items (which is incorrect)
and added a third item for a different price
 
public boolean addToCart(Item newItem) {
        if (cart.add(newItem)) {
            //return false;
            String code = newItem.getItemCode();
            for (int j = 0; j < cart.size(); j++) {
                Item it = (Item) cart.get(j);
                String curCode = it.getItemCode();
                if (curCode.equals(code)) {
                    it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                    cart.set(j, it);
               }
            }
        } else {
            //cart.add(newItem);
            return false;
        }
        currentNumberOfItems = newItem.getItemQuant();
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
        return true;
    }

Open in new window


Result 4:

Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        2
D1X2FSG        429.99        Western Digital Caviar Green 3TB HDD        2

Your current bill is $2419.94
Number of items in cart: 2

the bill amount is incorrect.

Experiment 5:
moved the totalPrice var to within the nested if (in the loop)
 
public boolean addToCart(Item newItem) {
        if (cart.add(newItem)) {
            //return false;
            String code = newItem.getItemCode();
            for (int j = 0; j < cart.size(); j++) {
                Item it = (Item) cart.get(j);
                String curCode = it.getItemCode();
                if (curCode.equals(code)) {
                    it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                    cart.set(j, it);
                    totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
                }
            }
        } else {
            //cart.add(newItem);
            return false;
        }
        currentNumberOfItems = newItem.getItemQuant();
        //this was moved because it returned the incorrect result
        //totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
        return true;
    }

Open in new window


Result 5:

Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        2
D1X2FSG        429.99        Western Digital Caviar Green 3TB HDD        2

Your current bill is $2809.9300000000003
Number of items in cart: 2

This bill amount is now correct, but the quantites are still not as they should be (2 of the first item and 1 of the third and should be showing two lines of data, not three)

Experiment 6:
I set some variables in order to see the return values
 
public ShoppingCart() {
        cart = new ArrayList();
        MyCart = "My Selected Items";
        totalPrice = 0.00;
        currentNumberOfItems = 0;
        code = null;
        curCode = null;
        qty1 = 0;
        qty2 = 0;
    }
    public boolean addToCart(Item newItem) {
        //above this line the cart is empty
        if (cart.add(newItem)) {//add an item
            code = newItem.getItemCode();
            for (int j = 0; j < cart.size(); j++) {
                Item it = (Item) cart.get(j);
                curCode = it.getItemCode();
                if (curCode.equals(code)) {
                    qty1 = it.getItemQuant();
                    qty2 = newItem.getItemQuant();
                    it.setItemQuant(it.getItemQuant() + newItem.getItemQuant());
                    cart.set(j, it);
                    totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
                }
            }
        } else {
            return false;
        }
        currentNumberOfItems = newItem.getItemQuant();
        return true;
    }

Open in new window


Result 6:

Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        3
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        2
D1X2FSG        429.99        Western Digital Caviar Green 3TB HDD        2

cart.totalPrice: 2809.9300000000003
cart.currentNumberOfItems: 2
code: D1X2FSG
curCode: D1X2FSG
it.getItemQuant: 1
newItem.getItemQuant: 1

I think I know what is happening.  The item at index j isn't being replaced, just shifted.  Instead of removing the identical line it is just being shifted downward in the list.  I tried to use cart.remove(j) but that emptied the list of course!

Still working on it...more results later.
0
 

Author Comment

by:g_currier
Comment Utility
This actually worked a lot easier:
GoShopping.java - note the changes in case 1
 
/*
 * Files:
 * Item.java
 * ShoppingCart.java
 * itemList.txt (Input)
 * CartSummary.txt (Output)
 *
 */
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:
                    ArrayList<String> listArray = new ArrayList<String>();
                    Item listItem1 = new Item();
                    Scanner input1 = new Scanner(inputFile).useDelimiter("\\-");
                    input = new Scanner(inputFile).useDelimiter("\\-");
//                    while (input1.hasNext()){
//                        String line1 = input1.nextLine();
//                        String[] lineItem1 = line1.split("\\-");
//                        String itemCode1 = lineItem1[0].trim();
//                        String strPrice1 = lineItem1[1];
//                        String itemName1 = lineItem1[2];
//                        double itemPrice1 = Double.parseDouble(strPrice1);
//                        listItem1.setItemCode(itemCode1);
//                        listItem1.setItemName(itemName1);
//                        listItem1.setItemQuant(1);
//                        listItem1.setItemPrice(itemPrice1);
//                        String a = listItem1.toString();
//                        listArray.add(a);
//                    }
                    System.out.println(listArray +"\n"+"Choose a code form the list of items.\n");
                    while (input.hasNextLine()) {

                        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")) {
                            int itemQuantity = 0;
                            System.out.println("How many would you like?\n");
                            itemQuantity = scanner.nextInt();
                            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("Item not added.\n\n");
                                
                            }
                        } else {
                            System.out.print("No items added");
                            
                        }
                    }
                    input.close();
                    break;
                case 2:
                    System.out.print(cart.toString()+"\n"+
                            "Running total: " + cart.totalPrice);

                    break;
                case 3:
                    cart.EmptyCart();
                    break;
                case 4:
                    //output to screen and file anf finalize the list with the trim function
                    System.out.print(cart.toString()+"\n"+
                            "Please Pay: " + cart.totalPrice);
                    cart.cartTrim();
                    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


and
Shopping.java
 
package TestPackage;

import java.util.ArrayList;
import javax.rmi.CORBA.Util;

public class ShoppingCart {

    private ArrayList cart;
    private String MyCart;
    String code;
    String curCode;
    int qty1;
    int qty2;
    
    private String name;
    int currentNumberOfItems;
    double totalPrice;

    public ShoppingCart() {
        cart = new ArrayList();
        MyCart = "My Selected Items";
        totalPrice = 0.00;
        currentNumberOfItems = 0;
        code = null;
        curCode = null;
        qty1 = 0;
        qty2 = 0;
    }
    public boolean addToCart(Item newItem) {
        if (!cart.add(newItem)) {//add an item
            System.out.println("Error adding Item to cart.");
            return false;
        }
        totalPrice += newItem.getItemQuant() * newItem.getItemPrice();
        //currentNumberOfItems = newItem.getItemQuant();
        return true;
    }

    public boolean inList(Item newItem) {
        return cart.contains(newItem);
    }

    public void EmptyCart() {
        currentNumberOfItems = 0;
        totalPrice = 0.00;
        cart.clear();
    }
    public double getItemTotal(double totalPrice) {
        this.totalPrice = totalPrice;
        return totalPrice;
    }
    public void cartTrim(){
        cart.trimToSize();
    }

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

Open in new window


I figured if I already had the ability to input the quantity manually, why not just use user input to set it?

in any case the input was correct and the totals add up.

Code           Price         Item                                        Quantity
D1X2FSF        389.99        Western Digital Caviar Black 3TB HDD        5
A1G4BFM        89.99        Atlas DDR3 1 GB Memory Module                10

Running total: 2849.85
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
So, did replacing of the item in the ArrayList finally worked for you?
0
 

Author Comment

by:g_currier
Comment Utility
the quantity can now be updated and so, onwards to using the item code in the same fashion and then creating a means to discount the items according based on the first letter of the code.  I'll post what I have in a new thread along with the revised classes.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
OK. I'm glad, it is all working, and we move forward incrementally.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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…
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

763 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

13 Experts available now in Live!

Get 1:1 Help Now