I did my best not to copy.. I swear.. Here is what I have this morning..

TestShoppingCart.java

import java.util.*;
     
public class TestShoppingCart {
    public static void main(String [] args){
    	//Create an array for 2 shopping carts (might need some guidance on how this will work)
    	ShoppingCart[]myCarts = new ShoppingCart[2];
    	for(int i = 0; i < myCarts.length; i++){
    		myCarts[i] = new ShoppingCart(size);
    	}
    	int choice;
    	String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
    	String enterQuantity = "Please enter a quantity";
    	storeItems[0] = new LineItem("Bananas" ,2.50, 0);
    	storeItems[1] = new LineItem("Apples" ,1.50, 0);
    	storeItems[2] = new LineItem("Oranges" ,3.50, 0);
    	storeItems[3] = new LineItem("Grapes" ,0.50, 0);
    	storeItems[4] = new LineItem("Cherries" ,0.10, 0);
     
    	//Prompt the user to select/Initialize a shopping cart
    	Scanner selectCart = new Scanner(System.in);
    	System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
    	int cartInput = selectCart.nextInt();
    	//ensure the user input is either 0 or 1
    	int userCart = ((cartInput + 1)%myCarts.length);
     
    	//The next section asks the user to select a cart, items and quantities and displays the content
    	do {
    		//read the next input from the user
    		Scanner input = new Scanner(System.in);
    		System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
    		choice = input.nextInt();
    		if(choice == 1){
    			//Prompt the user to select a shopping cart
    			selectCart = new Scanner(System.in);
    			System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
    			cartInput = selectCart.nextInt();
    			//ensure the user input is either 0 or 1
    			userCart = ((cartInput + 1)%mycarts.length);
    		}
    		else if(choice == 2){
    			//Prompt the user to select an item
    			System.out.println(itemList);
    			Scanner selectItem = new Scanner(System.in);
    			int addedItem = selectItem.nextInt();
     
    			//Prompt user to enter a quantity
    			System.out.println(enterQuantity);
    			Scanner selectQuantity = new Scanner(System.in);
    			int addedQuantity = selectQuantity.nextInt();
     
    			//Add the item and quantity to the cart
    			addedItem -=1;
    			//Set the quantity of the selected item to the cart
    			storeItems[addedItem].setQuantity(addedQuantity);
    			//Add the item to the cart
    			myCarts[userCart].addItem(storeItems[addItem]);
     
    		}
    		else if (choice == 3){
    			//Display Cart contents
    			System.out.println(ShoppingCart.getDisplayData());
    			//Display Cart total
    			System.out.println(ShoppingCart.getTotalCost());
    		}
    		else{
    			continue;
    		}
    	}while(choice != 4);
    }
}

ShoppingCart.java

import java.text.DecimalFormat;
import java.util.*;
    public class ShoppingCart {
    	private double totalCost;
    	private LineItem[] myItems;
    	private int max = 100;
    	int numberOfItems;
         
     
    	//Provide a constructor for this class
    	public ShoppingCart(int size){
    		max = size;
    		//Set every new cart to "empty"
    		this.totalCost = 0;
    		//Intialize the array
    		myItems = new LineItem[max]; 
    		numberOfItems = 0;
    	}
    //add a method to add a line item object to this class
     
    	public void addItem(LineItem newItemObject){
    		if(numberOfItems < max - 1){ //max - 1 due to the actual index
    		myItems[numberOfItems++] = newItemObject;

		//update the totalcost
		totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
    		}
     
    	}
     
    	//a method printing out the carts contents with the total cost of all the items/quantities
    	public String getDisplayData(){
    		DecimalFormat df = new DecimalFormat("#.##");
    		String output = "";
    		output += "Your shopping cart contains: \n";
    		output += "\n\t----------------------------------------------";
    		//Create a loop to display the contents and quantity of the selected cart
    			for(int x = 0; x < numberOfItems; x++){
    				//Append the string with a new lineItem
    				output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
    				myItems[x].productName + " @ " +
    				myItems[x].costPerItem + " = " +
    				myItems[x].costPerItem * myItems[x].itemQuantity))
    				;
    			}
    			output += "\n\tTotal : " + myCarts.totalCost;
    			output += "\n\t------------------------------------------";
        	
		return output; 

    	}
    	public double getTotalCost(){
    		return totalCost;
    	}
}

LineItem.java

import java.util.*;
    class LineItem {
    	String productName;
    	double costPerItem;
    	int itemQuantity;
     
    public LineItem(String productName, double costPerItem, int itemQuantity){
    	this.costPerItem = costPerItem;
    	this.productName = productName;
    	this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
    	return costPerItem;
    }
    public String getProductName(){
    	return productName;
    }
    public int getItemQuantity(){
    	return itemQuantity;
    }
    public void setQuantity(int qty){
    	itemQuantity = qty;
    }
}

looks good, you can't test it at work can you?

sadly no.. unless I wanted to type it from one network to another.. and thats a lot of typing!

TestShoppingCart.java

Errors -

"Internal error; cannot instantiate ShoppinCart(int) at ShoppingCart()

myCarts[i] = new ShoppingCart(size);

Cannot find Symbol - Variable storeItems (Assuming because we never declared it?

    storeItems[0] = new LineItem("Bananas" ,2.50, 0);
    storeItems[1] = new LineItem("Apples" ,1.50, 0);
    storeItems[2] = new LineItem("Oranges" ,3.50, 0);
    storeItems[3] = new LineItem("Grapes" ,0.50, 0);
    storeItems[4] = new LineItem("Cherries" ,0.10, 0);

More of the same

            storeItems[addedItem].setQuantity(addedQuantity);
            //Add the item to the cart
            myCarts[userCart].addItem(storeItems[addItem]);

Lastly -

non static method getDisplayData() cannot be referenced from a static context - I tried switching this around a bit and cannot figure out how to get the two to talk nice.

            //Display Cart contents
            System.out.println(ShoppingCart.getDisplayData());
            //Display Cart total
            System.out.println(ShoppingCart.getTotalCost());

Here is the full TestShoppingCart.java

import java.util.*;

public class TestShoppingCart {
    public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[]myCarts = new ShoppingCart[2];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(size);
        }
        int choice;
        String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
        String enterQuantity = "Please enter a quantity";
        storeItems[0] = new LineItem("Bananas" ,2.50, 0);
        storeItems[1] = new LineItem("Apples" ,1.50, 0);
        storeItems[2] = new LineItem("Oranges" ,3.50, 0);
        storeItems[3] = new LineItem("Grapes" ,0.50, 0);
        storeItems[4] = new LineItem("Cherries" ,0.10, 0);

        //Prompt the user to select/Initialize a shopping cart
        Scanner selectCart = new Scanner(System.in);
        System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
        int cartInput = selectCart.nextInt();
        //ensure the user input is either 0 or 1
        int userCart = ((cartInput + 1)%myCarts.length);

        //The next section asks the user to select a cart, items and quantities and displays the content
        do {
            //read the next input from the user
            Scanner input = new Scanner(System.in);
            System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
            choice = input.nextInt();
            if(choice == 1){
                //Prompt the user to select a shopping cart
                selectCart = new Scanner(System.in);
                System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
                cartInput = selectCart.nextInt();
                //ensure the user input is either 0 or 1
                userCart = ((cartInput + 1)%myCarts.length);
            }
            else if(choice == 2){
                //Prompt the user to select an item
                System.out.println(itemList);
                Scanner selectItem = new Scanner(System.in);
                int addedItem = selectItem.nextInt();

                //Prompt user to enter a quantity
                System.out.println(enterQuantity);
                Scanner selectQuantity = new Scanner(System.in);
                int addedQuantity = selectQuantity.nextInt();

                //Add the item and quantity to the cart
                addedItem -=1;
                //Set the quantity of the selected item to the cart
                storeItems[addedItem].setQuantity(addedQuantity);
                //Add the item to the cart
                myCarts[userCart].addItem(storeItems[addItem]);

            }
            else if (choice == 3){
                //Display Cart contents
                System.out.println(ShoppingCart.getDisplayData());
                //Display Cart total
                System.out.println(ShoppingCart.getTotalCost());
            }
            else{
                continue;
            }
        }while(choice != 4);
    }
}

ShoppingCart.java

only error right now

cannot find symbol myCarts (thinks it is from this class)(do I even need this line?

output += "\n\tTotal : " + myCarts.totalCost;

Full ShoppingCart.java

import java.util.*;
    public class ShoppingCart {
        private double totalCost;
        private LineItem[] myItems;
        private int max = 100;
        int numberOfItems;


        //Provide a constructor for this class
        public ShoppingCart(int size){
        max = size;
        //Set every new cart to "empty"
        this.totalCost = 0;
        //Intialize the array
        myItems = new LineItem[max];
        numberOfItems = 0;
    }
        //add a method to add a line item object to this class

    public void addItem(LineItem newItemObject){
        if(numberOfItems < max - 1){ //max - 1 due to the actual index
        myItems[numberOfItems++] = newItemObject;

        //update the totalcost
        totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
        }

    }

    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
        //DecimalFormat df = new DecimalFormat("#.##");
        String output = "";
        output += "Your shopping cart contains: \n";
        output += "\n\t----------------------------------------------";
        //Create a loop to display the contents and quantity of the selected cart
        for(int x = 0; x < numberOfItems; x++){
            //Append the string with a new lineItem
            output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
            myItems[x].productName + " @ " +
            myItems[x].costPerItem + " = " +
            myItems[x].costPerItem * myItems[x].itemQuantity;
        }
        output += "\n\tTotal : " + myCarts.totalCost;
        output += "\n\t------------------------------------------";

        return output;

    }
    public double getTotalCost(){
        return totalCost;
    }
}

LineItem.java - No errors yet. :-)

import java.util.*;
    class LineItem {
        String productName;
        double costPerItem;
        int itemQuantity;

    public LineItem(String productName, double costPerItem, int itemQuantity){
        this.costPerItem = costPerItem;
        this.productName = productName;
        this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
        return costPerItem;
    }
    public String getProductName(){
        return productName;
    }
    public int getItemQuantity(){
        return itemQuantity;
    }
    public void setQuantity(int qty){
        itemQuantity = qty;
    }
}

Assuming because we never declared it?

exactly

non static method getDisplayData() cannot be referenced from a static context

getDataDisplay() and getTotal() are non static methods, yet you are calling them from the class name ShoppingCart.getTotal(); which is the way to call static methods. Call them from a ShoppingCart OBJECT .. like one of the carts in your cart array, probably at index "userCart" ;)

cannot find symbol myCarts

myCarts is the ShoppingCart array you have in your main. totalCost is local in ShoppingCart, just use it without "myCarts"!

I'm looking to understand this better, not to have you just tell me the answer.


LineItem.java and ShoppingCart.java now have no errors. However TestShoppingCart.java is still loaded.

I'm not even sure if this is english... It does not like the variable "size"

"Internal error; cannot instantiate ShoppinCart(int) at ShoppingCart()"

myCarts[i] = new ShoppingCart(size);

I still do not understand how to initialize the storeItems array. I cannot figure it out. Its not a typical array, Are the numbers in the array actually a string? or are they doubles and integers?

It does not like this line: I'm pretty sure I fubar'd this line. I think it needs to be added... lol I'll change that...

myCarts[userCart].addItem(storeItems[addItem]);

I also dont understand how to reference the object. for the display piece.

here are the current files:

TestShoppingCart.java

import java.util.*;
     
public class TestShoppingCart {
    public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[]myCarts = new ShoppingCart[2];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(size);
        }
        int choice;
        String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
        String enterQuantity = "Please enter a quantity";
        storeItems[0] = new LineItem("Bananas" ,2.50, 0);
        storeItems[1] = new LineItem("Apples" ,1.50, 0);
        storeItems[2] = new LineItem("Oranges" ,3.50, 0);
        storeItems[3] = new LineItem("Grapes" ,0.50, 0);
        storeItems[4] = new LineItem("Cherries" ,0.10, 0);
     
        //Prompt the user to select/Initialize a shopping cart
        Scanner selectCart = new Scanner(System.in);
        System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
        int cartInput = selectCart.nextInt();
        //ensure the user input is either 0 or 1
        int userCart = ((cartInput + 1)%myCarts.length);
     
        //The next section asks the user to select a cart, items and quantities and displays the content
        do {
            //read the next input from the user
            Scanner input = new Scanner(System.in);
            System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
            choice = input.nextInt();
            if(choice == 1){
                //Prompt the user to select a shopping cart
                selectCart = new Scanner(System.in);
                System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
                cartInput = selectCart.nextInt();
                //ensure the user input is either 0 or 1
                userCart = ((cartInput + 1)%myCarts.length);
            }
            else if(choice == 2){
                //Prompt the user to select an item
                System.out.println(itemList);
                Scanner selectItem = new Scanner(System.in);
                int addedItem = selectItem.nextInt();
     
                //Prompt user to enter a quantity
                System.out.println(enterQuantity);
                Scanner selectQuantity = new Scanner(System.in);
                int addedQuantity = selectQuantity.nextInt();
     
                //Add the item and quantity to the cart
                addedItem -=1;
                //Set the quantity of the selected item to the cart
                storeItems[addedItem].setQuantity(addedQuantity);
                //Add the item to the cart
                myCarts[userCart].addItem(storeItems[addItem]);
     
            }
            else if (choice == 3){
                //Display Cart contents
                System.out.println(getDisplayData());
                //Display Cart total
                System.out.println(getTotalCost());
            }
            else{
                continue;
            }
        }while(choice != 4);
    }
}

ShoppingCart.java

import java.util.*;
    public class ShoppingCart {
        private double totalCost;
        private LineItem[] myItems;
        private int max = 100;
        int numberOfItems;
     
     
        //Provide a constructor for this class
        public ShoppingCart(int size){
        max = size;
        //Set every new cart to "empty"
        this.totalCost = 0;
        //Intialize the array
        myItems = new LineItem[max];
        numberOfItems = 0;
    }
        //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
        if(numberOfItems < max - 1){ //max - 1 due to the actual index
        myItems[numberOfItems++] = newItemObject;
     
        //update the totalcost
        totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
        }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
        //DecimalFormat df = new DecimalFormat("#.##");
        String output = "";
        output += "Your shopping cart contains: \n";
        output += "\n\t----------------------------------------------";
        //Create a loop to display the contents and quantity of the selected cart
        for(int x = 0; x < numberOfItems; x++){
            //Append the string with a new lineItem
            output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
            myItems[x].productName + " @ " +
            myItems[x].costPerItem + " = " +
            myItems[x].costPerItem * myItems[x].itemQuantity;
        }
        output += "\n\tTotal : " + totalCost;
        output += "\n\t------------------------------------------";
     
        return output;
     
    }
    public double getTotalCost(){
        return totalCost;
    }
}

LineItem.java

import java.util.*;
    class LineItem {
        String productName;
        double costPerItem;
        int itemQuantity;
     
    public LineItem(String productName, double costPerItem, int itemQuantity){
        this.costPerItem = costPerItem;
        this.productName = productName;
        this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
        return costPerItem;
    }
    public String getProductName(){
        return productName;
    }
    public int getItemQuantity(){
        return itemQuantity;
    }
    public void setQuantity(int qty){
        itemQuantity = qty;
    }
}
public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[]myCarts = new ShoppingCart[2];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(size);
        }

Here the problem is with the argument you send to the ShoppingCart constructor, there is only 1 constructor, it excpects a int variable. Within that constructor, the argument is gonna be refered to as "size" because thats the name you gave in it's signature. so here it acts as if you declared "size" inside the constructor, it's scope is from the openning bracket{ to the closing bracket} of said constructor, anywhere outside those brackets, the variable called "size" is unexistant.

You try to instanciate your shopping cart by calling the constructor and giving it soemthing called size, yet you have no variable in that specific scope that is declared as "size". Therefore the error is not with the constructor, it's with the variable you are trying to give it, it doesnt exist, you can declare a variable give it some value and then pass it as an argument, but i would advise agaisnt calling it "size" for now as you seem to mix and match variable names out of their scopes, another solution would be to hardcode the value you give the constructor in the loop by directly passing an int :

myCarts[i] = new ShoppingCart(25);

now on to the other error :

storeItems[addedItem].setQuantity(addedQuantity);
myCarts[userCart].addItem(storeItems[addItem]);

Here you have 3 int variables(userCart & addedItem & addedQuantity), 2 arrays (myCarts & storeItems)and 2 methods (.setQuantity(int) from LineItem & .addItem(LineItem) from ShoppingCart )

the first line is fine, it takes the LineItem object at the index "addedItem" of the "storeItems" array and call its .setQuantity() method passing it "addedQuantity" as an argument. this sets the class variable "itemQuantity" inside the LineItem object to "addedQuantity"

the second line is 2 characters away from being right ;
it takes the ShoppingCart object at the index "userCart" of the "myCarts" array and call its .addItem() method passing it the LineItem object at the index "addItem" of the "storeItems" array as an argument.

The problem with this is that addItem() method expects an argument of type "LineItem" which you are trying to retrieve from the "storeItems" array, BUT , the array is navigated with the use of indexes in the form of integer numbers, and you are trying to retrieve from storeItems the LineItem at position "addItem", here addItem is not an integer, there are no variables with that name in this scope. It is probable you have mistaken "addedItem", the variable we want in this case, with .addItem() method.

so the correct line would be :

myCarts[userCart].addItem(storeItems[add[I][B][U]ed[/U][/B][/I]Item]);

Edit: Your display method looks fine, what is wrong with it?

commented: very helpful! +2

Thanks for your last post. It was very helpful!

So I still have the problem of initiating the storeItems Array.. I've googled everything I can and I cannot figure it out. I've tried several variations.. thoughts on how to send me down the right path?

TestShoppingCart.java

import java.util.*;
     
public class TestShoppingCart {
    public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[]myCarts = new ShoppingCart[2];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(25);
        }
        int choice;
        String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
        String enterQuantity = "Please enter a quantity";
        storeItems[0] = new LineItem("Bananas" ,2.50, 0);
        storeItems[1] = new LineItem("Apples" ,1.50, 0);
        storeItems[2] = new LineItem("Oranges" ,3.50, 0);
        storeItems[3] = new LineItem("Grapes" ,0.50, 0);
        storeItems[4] = new LineItem("Cherries" ,0.10, 0);
     
        //Prompt the user to select/Initialize a shopping cart
        Scanner selectCart = new Scanner(System.in);
        System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
        int cartInput = selectCart.nextInt();
        //ensure the user input is either 0 or 1
        int userCart = ((cartInput + 1)%myCarts.length);
     
        //The next section asks the user to select a cart, items and quantities and displays the content
        do {
            //read the next input from the user
            Scanner input = new Scanner(System.in);
            System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
            choice = input.nextInt();
            if(choice == 1){
                //Prompt the user to select a shopping cart
                selectCart = new Scanner(System.in);
                System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
                cartInput = selectCart.nextInt();
                //ensure the user input is either 0 or 1
                userCart = ((cartInput + 1)%myCarts.length);
            }
            else if(choice == 2){
                //Prompt the user to select an item
                System.out.println(itemList);
                Scanner selectItem = new Scanner(System.in);
                int addedItem = selectItem.nextInt();
     
                //Prompt user to enter a quantity
                System.out.println(enterQuantity);
                Scanner selectQuantity = new Scanner(System.in);
                int addedQuantity = selectQuantity.nextInt();
     
                //Add the item and quantity to the cart
                addedItem -=1;
                //Set the quantity of the selected item to the cart
                storeItems[addedItem].setQuantity(addedQuantity);
                //Add the item to the cart
                myCarts[userCart].addItem(storeItems[addedItem]);
     
            }
            else if (choice == 3){
                //Display Cart contents
                System.out.println(getDisplayData());
                //Display Cart total
                System.out.println(getTotalCost());
            }
            else{
                continue;
            }
        }while(choice != 4);
    }
}

ShoppingCart.java

import java.util.*;
public class ShoppingCart {
    private double totalCost;
    private LineItem[] myItems;
    private int max = 100;
    int numberOfItems;
        
    //Provide a constructor for this class
    public ShoppingCart(int size){
        max = size;
        //Set every new cart to "empty"
        this.totalCost = 0;
        //Intialize the array
        myItems = new LineItem[max];
        numberOfItems = 0;
    }
    //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
        if(numberOfItems < max - 1){ //max - 1 due to the actual index
            myItems[numberOfItems++] = newItemObject;
     
            //update the totalcost
            totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
        }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
        //DecimalFormat df = new DecimalFormat("#.##");
        String output = "";
        output += "Your shopping cart contains: \n";
        output += "\n\t----------------------------------------------";
        //Create a loop to display the contents and quantity of the selected cart
        for(int x = 0; x < numberOfItems; x++){
            //Append the string with a new lineItem
            output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
            myItems[x].productName + " @ " +
            myItems[x].costPerItem + " = " +
            myItems[x].costPerItem * myItems[x].itemQuantity;
        }
        output += "\n\tTotal : " + totalCost;
        output += "\n\t------------------------------------------";
     
        return output; 
    }
    public double getTotalCost(){
        return totalCost;
    }
}

LineItem.java

import java.util.*;
class LineItem {
    String productName;
    double costPerItem;
    int itemQuantity;
     
    public LineItem(String productName, double costPerItem, int itemQuantity){
        this.costPerItem = costPerItem;
        this.productName = productName;
        this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
        return costPerItem;
    }
    public String getProductName(){
        return productName;
    }
    public int getItemQuantity(){
        return itemQuantity;
    }
    public void setQuantity(int qty){
        itemQuantity = qty;
    }
}

you are initiating it just fine, the problem is it was never declared...

LineItem[] storeItems = new LineItem[5];

ps: it wasn't me who downrated the post above. :S

you are initiating it just fine, the problem is it was never declared...

LineItem[] storeItems = new LineItem[5];

ps: it wasn't me who downrated the post above. :S

ok.. So everything looks good except for calling the display methods from ShoppingCart.java. Earlier you stated "getDataDisplay() and getTotal() are non static methods, yet you are calling them from the class name ShoppingCart.getTotal(); which is the way to call static methods. Call them from a ShoppingCart OBJECT .. like one of the carts in your cart array, probably at index "userCart" "

Can you break this down a little further for me?

Here is the code as it stands:

TestShoppingCart.java

import java.util.*;
     
public class TestShoppingCart {
    public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[] myCarts = new ShoppingCart[2];
        LineItem[] storeItems = new LineItem[5];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(25);
        }
        int choice;
        String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
        String enterQuantity = "Please enter a quantity";
        storeItems[0] = new LineItem("Bananas" ,2.50, 0);
        storeItems[1] = new LineItem("Apples" ,1.50, 0);
        storeItems[2] = new LineItem("Oranges" ,3.50, 0);
        storeItems[3] = new LineItem("Grapes" ,0.50, 0);
        storeItems[4] = new LineItem("Cherries" ,0.10, 0);
     
        //Prompt the user to select/Initialize a shopping cart
        Scanner selectCart = new Scanner(System.in);
        System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
        int cartInput = selectCart.nextInt();
        //ensure the user input is either 0 or 1
        int userCart = ((cartInput + 1)%myCarts.length);
     
        //The next section asks the user to select a cart, items and quantities and displays the content
        do {
            //read the next input from the user
            Scanner input = new Scanner(System.in);
            System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
            choice = input.nextInt();
            if(choice == 1){
                //Prompt the user to select a shopping cart
                selectCart = new Scanner(System.in);
                System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
                cartInput = selectCart.nextInt();
                //ensure the user input is either 0 or 1
                userCart = ((cartInput + 1)%myCarts.length);
            }
            else if(choice == 2){
                //Prompt the user to select an item
                System.out.println(itemList);
                Scanner selectItem = new Scanner(System.in);
                int addedItem = selectItem.nextInt();
     
                //Prompt user to enter a quantity
                System.out.println(enterQuantity);
                Scanner selectQuantity = new Scanner(System.in);
                int addedQuantity = selectQuantity.nextInt();
     
                //Add the item and quantity to the cart
                addedItem -=1;
                //Set the quantity of the selected item to the cart
                storeItems[addedItem].setQuantity(addedQuantity);
                //Add the item to the cart
                myCarts[userCart].addItem(storeItems[addedItem]);
     
            }
            else if (choice == 3){
                //Display Cart contents
                System.out.println(getDisplayData(myCarts[userCart]));
                //Display Cart total
                System.out.println(getTotalCost(myCarts[userCart]));
            }
            else{
                continue;
            }
        }while(choice != 4);
    }
}

ShoppingCart.java

import java.util.*;
public class ShoppingCart {
    private double totalCost;
    private LineItem[] myItems;
    private int max = 100;
    int numberOfItems;
        
    //Provide a constructor for this class
    public ShoppingCart(int size){
        max = size;
        //Set every new cart to "empty"
        this.totalCost = 0;
        //Intialize the array
        myItems = new LineItem[max];
        numberOfItems = 0;
    }
    //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
        if(numberOfItems < max - 1){ //max - 1 due to the actual index
            myItems[numberOfItems++] = newItemObject;
     
            //update the totalcost
            totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
        }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
        //DecimalFormat df = new DecimalFormat("#.##");
        String output = "";
        output += "Your shopping cart contains: \n";
        output += "\n\t----------------------------------------------";
        //Create a loop to display the contents and quantity of the selected cart
        for(int x = 0; x < numberOfItems; x++){
            //Append the string with a new lineItem
            output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
            myItems[x].productName + " @ " +
            myItems[x].costPerItem + " = " +
            myItems[x].costPerItem * myItems[x].itemQuantity;
        }
        output += "\n\tTotal : " + totalCost;
        output += "\n\t------------------------------------------";
     
        return output; 
    }
    public double getTotalCost(){
        return totalCost;
    }
}

LineItem.java

import java.util.*;
class LineItem {
    String productName;
    double costPerItem;
    int itemQuantity;
     
    public LineItem(String productName, double costPerItem, int itemQuantity){
        this.costPerItem = costPerItem;
        this.productName = productName;
        this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
        return costPerItem;
    }
    public String getProductName(){
        return productName;
    }
    public int getItemQuantity(){
        return itemQuantity;
    }
    public void setQuantity(int qty){
        itemQuantity = qty;
    }
}

Earlier you stated "getDataDisplay() and getTotal() are non static methods, yet you are calling them from the class name ShoppingCart.getTotal(); which is the way to call static methods. Call them from a ShoppingCart OBJECT .. like one of the carts in your cart array, probably at index "userCart" "

and with this you made :

else if (choice == 3){
    //Display Cart contents
    System.out.println(getDisplayData(myCarts[userCart]));
    //Display Cart total
    System.out.println(getTotalCost(myCarts[userCart]));
}

let's ignore the println() to explain this problem , just take the printed parts :

getTotalCost(myCarts[userCart])

alright so, getTotalCost is a method, it does not take any argument, it is non static, and it belongs to ShoppingCart. You are calling it like it's defined localy which isn't the case, you could call a method without specifying where it's from in the event that it was written in the same class, but it's not. You are also calling it with an argument, and if you look at line 50 of ShoppingCart.java, that method returns a double and takes no arguments : public double getTotalCost()

the argument you are giving it is the current ShoppingCart from "myCarts" array, THAT is what is gonna be calling the method, so you were rather close.

fix :

else if (choice == 3){
    //Display Cart contents
    System.out.println(myCarts[userCart].getDisplayData());
    //Display Cart total

    //two things bout this next line :
    // 1 ) i added ( ""+ ) before the call to getTotalCost, this is because
    //     println() takes a string argument and getTotalCost returns a double,
    //     calling .ToString() would've been fine too

    // 2 ) it is not necessary to print out the total here as you already take care of          
    //     including it in the DisplayData method's return String.

    System.out.println(""+myCarts[userCart].getTotalCost());
}
commented: Excellent helper! Breaks things down to the beginners levels. Cant ask for anything more than that!!! Thank you very much! +2

Awesome!!! I have some cleanup to do on the code! and some additional notes to take, a UML diagram, but all of that would not have been possible without your help! Thank you very much!

I'll post the final solution in a few days.

good to hear man :) glad i could help!

I'm trying to format the out put so that the total cost will be $#.##. However I am not successful.

Thoughts?

TestShoppingCart.java

import java.util.Scanner;
  
public class TestShoppingCart {
    public static void main(String [] args){
        //Create an array for 2 shopping carts (might need some guidance on how this will work)
        ShoppingCart[] myCarts = new ShoppingCart[2];
        LineItem[] storeItems = new LineItem[5];
        for(int i = 0; i < myCarts.length; i++){
            myCarts[i] = new ShoppingCart(25);
        }
        int choice;
        //Create 2 constant string variables
        String itemList = "Please select one of our items:\n1)Bananas\n2)Apples\n3)Oranges]\n4)Grapes\n5)Cherries";
        String enterQuantity = "Please enter a quantity";
        //Create the shopping cart line items
        storeItems[0] = new LineItem("Bananas" ,2.50, 0);
        storeItems[1] = new LineItem("Apples" ,1.50, 0);
        storeItems[2] = new LineItem("Oranges" ,3.50, 0);
        storeItems[3] = new LineItem("Grapes" ,0.50, 0);
        storeItems[4] = new LineItem("Cherries" ,0.10, 0);
     
        //Prompt the user to select/Initialize a shopping cart
        Scanner selectCart = new Scanner(System.in);
        System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
        int cartInput = selectCart.nextInt();
        //ensure the user input is either 0 or 1
        int userCart = ((cartInput + 1)%myCarts.length);
     
        //The next section asks the user to select a cart, items and quantities and displays the content
        do {
            //read the next input from the user
            Scanner input = new Scanner(System.in);
            System.out.println("Please select and option:\n1)Change your shopping cart.\n2)To add an item to your shopping cart.\n3)To view your cart and total.\n4)Quit");
            choice = input.nextInt();
            if(choice == 1){
                //Prompt the user to select a shopping cart
                selectCart = new Scanner(System.in);
                System.out.println("Please select your shopping cart: \n1)Shopping Cart 1.\n2)Shopping Cart 2");
                cartInput = selectCart.nextInt();
                //ensure the user input is either 0 or 1
                userCart = ((cartInput + 1)%myCarts.length);
            }
            else if(choice == 2){
                //Prompt the user to select an item
                System.out.println(itemList);
                Scanner selectItem = new Scanner(System.in);
                int addedItem = selectItem.nextInt();
     
                //Prompt user to enter a quantity
                System.out.println(enterQuantity);
                Scanner selectQuantity = new Scanner(System.in);
                int addedQuantity = selectQuantity.nextInt();
     
                //Add the item and quantity to the cart
                addedItem -=1;
                //Set the quantity of the selected item to the cart
                storeItems[addedItem].setQuantity(addedQuantity);
                //Add the item to the cart
                myCarts[userCart].addItem(storeItems[addedItem]);
     
            }
            else if (choice == 3){
                //Display Cart contents & Total
                System.out.println(myCarts[userCart].getDisplayData());
            }
            else{
                continue;
            }
        }while(choice != 4);
    }
}

ShoppingCart.java

import java.text.DecimalFormat;
public class ShoppingCart {
    private double totalCost;
    private LineItem[] myItems;
    private int max = 100;
    int numberOfItems;
        
    //Provide a constructor for this class
    public ShoppingCart(int size){
        max = size;
        //Set every new cart to "empty"
        this.totalCost = 0;
        //Intialize the array
        myItems = new LineItem[max];
        numberOfItems = 0;
    }
    //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
        if(numberOfItems < max - 1){ //max - 1 due to the actual index
            myItems[numberOfItems++] = newItemObject;
     
            //update the totalcost
            totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
        }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
        DecimalFormat myFormat = new DecimalFormat("#.##");
        String output = "";
        output += "Your shopping cart contains: \n";
        output += "\n\t----------------------------------------------";
        //Create a loop to display the contents and quantity of the selected cart
        for(int x = 0; x < numberOfItems; x++){
            //Append the string with a new lineItem
            output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
            myItems[x].productName + " @ " +
            myFormat.format(myItems[x].costPerItem) + " = $" +
            myItems[x].costPerItem * myItems[x].itemQuantity;
        }
        output += "\n\tTotal : $" + myFormat.format(totalCost);
        output += "\n\t----------------------------------------------";
     
        return output; 
    }
    public double getTotalCost(){
        return totalCost;
    }
}

LineItem.java

class LineItem {
    String productName;
    double costPerItem;
    int itemQuantity;
     
    public LineItem(String productName, double costPerItem, int itemQuantity){
        this.costPerItem = costPerItem;
        this.productName = productName;
        this.itemQuantity = itemQuantity;
    }
    public double getCostPerItem(){
        return costPerItem;
    }
    public String getProductName(){
        return productName;
    }
    public int getItemQuantity(){
        return itemQuantity;
    }
    public void setQuantity(int qty){
        itemQuantity = qty;
    }
}

df = new DecimalFormat("0.00$");
will force at least 1 number on the left and 2 decimals, if you format " 22 " with this it's going to return "22.00$"

So where did I go wrong?

import java.text.DecimalFormat;
    public class ShoppingCart {
    private double totalCost;
    private LineItem[] myItems;
    private int max = 100;
    int numberOfItems;
     
    //Provide a constructor for this class
    public ShoppingCart(int size){
    max = size;
    //Set every new cart to "empty"
    this.totalCost = 0;
    //Intialize the array
    myItems = new LineItem[max];
    numberOfItems = 0;
    }
    //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
    if(numberOfItems < max - 1){ //max - 1 due to the actual index
    myItems[numberOfItems++] = newItemObject;
     
    //update the totalcost
    totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
    }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
    DecimalFormat myFormat = new DecimalFormat("#.##");
    String output = "";
    output += "Your shopping cart contains: \n";
    output += "\n\t----------------------------------------------";
    //Create a loop to display the contents and quantity of the selected cart
    for(int x = 0; x < numberOfItems; x++){
    //Append the string with a new lineItem
    output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
    myItems[x].productName + " @ " +
    myFormat.format(myItems[x].costPerItem) + " = $" +
    myItems[x].costPerItem * myItems[x].itemQuantity;
    }
    output += "\n\tTotal : $" + myFormat.format(totalCost);
    output += "\n\t----------------------------------------------";
     
    return output;
    }
    public double getTotalCost(){
    return totalCost;
    }
    }

So where did I go wrong?

import java.text.DecimalFormat;
    public class ShoppingCart {
    private double totalCost;
    private LineItem[] myItems;
    private int max = 100;
    int numberOfItems;
     
    //Provide a constructor for this class
    public ShoppingCart(int size){
    max = size;
    //Set every new cart to "empty"
    this.totalCost = 0;
    //Intialize the array
    myItems = new LineItem[max];
    numberOfItems = 0;
    }
    //add a method to add a line item object to this class
     
    public void addItem(LineItem newItemObject){
    if(numberOfItems < max - 1){ //max - 1 due to the actual index
    myItems[numberOfItems++] = newItemObject;
     
    //update the totalcost
    totalCost += newItemObject.costPerItem * newItemObject.itemQuantity;
    }
     
    }
     
    //a method printing out the carts contents with the total cost of all the items/quantities
    public String getDisplayData(){
    DecimalFormat myFormat = new DecimalFormat("#.##");
    String output = "";
    output += "Your shopping cart contains: \n";
    output += "\n\t----------------------------------------------";
    //Create a loop to display the contents and quantity of the selected cart
    for(int x = 0; x < numberOfItems; x++){
    //Append the string with a new lineItem
    output += "\n\tItem : " + myItems[x].itemQuantity + " x " +
    myItems[x].productName + " @ " +
    myFormat.format(myItems[x].costPerItem) + " = $" +
    myItems[x].costPerItem * myItems[x].itemQuantity;
    }
    output += "\n\tTotal : $" + myFormat.format(totalCost);
    output += "\n\t----------------------------------------------";
     
    return output;
    }
    public double getTotalCost(){
    return totalCost;
    }
    }

check out this small snippet which might shed some light:

import java.text.DecimalFormat;
import java.text.NumberFormat;
 
public class DecimalFormatExample
{
  public static void main(String args[])
  {
  double amount = 2192.015;
  NumberFormat formatter = new DecimalFormat("#.##");
  System.out.println("The Decimal Value is:"+formatter.format(amount));//The Decimal Value is:2192.02
  }
}

This also is not the best:

myFormat.format(myItems[x].costPerItem)

because you are refering directly to the variable, you have a method getCostPerItem() so try:

myFormat.format(myItems[x].getCostPerItem())

Maybe also add a few prinln's to see what value is being brought through before being formatted, and what value looks like after being formated

check out this small snippet which might shed some light:

import java.text.DecimalFormat;
import java.text.NumberFormat;
 
public class DecimalFormatExample
{
  public static void main(String args[])
  {
  double amount = 2192.015;
  NumberFormat formatter = new DecimalFormat("#.##");
  System.out.println("The Decimal Value is:"+formatter.format(amount));//The Decimal Value is:$2192.02
  }
}

Hey genetix, although it is not "wrong" to instanciate your formatter variable as a DecimalFormat object while it is a NumberFormat variable since DecimalFormat is a subclass of NumberFormat, it is useless in this situation. "Encapsulation" is the oop property that enable this to be syntaxly correct, but you do not require the use of encapsulation in this example, so for simplicity's sake, you shouldn't use it.

if you need a DecimalFormat use one, if you want a NumberFormat then use that.

private DecimalFormat df= new DecimalFormat("0.00$");
private NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CANADA);

both these lines are valid and they will respectively create this output when formating "37610" :

37610,00$
$37,610.00

(notice here the DecimalFormat put a comma instead of a period for the first output, this is because it used my machine's local which is currently french canadian.)

@jpsider :

your problem is the use of the "#" character instead of "0" for your formatting mask, "0" will force a zero if the number you are formatting doesnt have a value for that specific position while "#" will only display if it's present.

take :

private DecimalFormat df= new DecimalFormat("000000.00#$");

System.out.println("no decimals with # : " + df.format(3456));
System.out.println("1 decimals with # : " + df.format(3456.1));
System.out.println("3 decimals with # : " + df.format(3456.789));

df= new DecimalFormat("000000.00$");

System.out.println("no decimals without # : " + df.format(3456)); 
System.out.println("1 decimals without # : " + df.format(3456.1)); 
System.out.println("3 decimals without # : " + df.format(3456.789)); //lost of decimal here

this would print out :

no decimals with # : 003456.00$
1 decimals with # : 003456.10$
3 decimals with # : 003456.789$
no decimals without # : 003456.00$
1 decimals without # : 003456.10$
3 decimals without # : 003456.78$

commented: Superb example! Helped 100% +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.