Joe Joe - 1 month ago 6
Java Question

Objects are being overwritten when adding a new Object to an array

I am working on an assignment for school and cannot figure why my items are being overwritten in my shopping cart class. If it were up to me id be using an arraylist but the assignment calls for an array of Items.

package jjobrien_assignement_4;


import java.util.Arrays;
import java.util.Scanner;

public class ShoppingCart extends Shopper{

private static final int DEFAULT_SIZE = 10;

String userName;

Item[] cart;

int itemCount = 0;
/**
* ShoppingCart default constructor
*/
public ShoppingCart(){
userName = "";
cart = new Item[DEFAULT_SIZE];
}
/**
* Shopping cart overloaded constructor
* @param aUserName
*/

public ShoppingCart(String aUserName){
userName = aUserName;
cart = new Item[DEFAULT_SIZE];
}
/**
* Adds a single item to the array cart[]
* @param cart
* @return
*/

public void addItem(Item theItem){

for(int i = 0; i < DEFAULT_SIZE; i++){

if(cart[i] == null){
System.out.print(i);
cart[i]= theItem;
itemCount += 1;
System.out.print(cart[i]);
break;
} //System.out.print(cart[i]);

}

}

public String removeItem(){
return "";
}
/**
*
* @param cleared
* @return cleared
* Will clear every object inside of the array cart[]
* by setting all valuse in the cart[] to null.
*/
public boolean clear(boolean cleared){
for(int i = 0; i < cart.length; i++){
cart[i] = null;
}

cleared = true;
itemCount = 0;
return cleared;
}

public String indexOf(){
return "";
}
/**
* Grabs single item from array to return to shopper
* @return
*/
public String getItem(){
String theItem = "";
for(int i = 0; i < itemCount; i++){
theItem = cart[i].getProductName();
}

return theItem;
}

public String showAll(String all){

for(int i = 0; i < itemCount; i++){
all += cart[i].getProductName() + " $"
+ cart[i].getPrice() + "\n";
}
return all;

}
/**
*
* @return
* Adds total cost and divides by item count to get avgCost
*/
public double showAverageCost(){
double avgCost = 0;
double totalCartCost = 0;
double singleItemCost = 0;

for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}

avgCost = totalCartCost/itemCount;

return avgCost;
}

/**
*
* @param totalCartCost
* @return
* Calculates total cost by getting each price
* of all existing items in the array cart[].
*/

public double totalCost(double totalCartCost){
double singleItemCost = 0;
for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}
return totalCartCost;
}

/**
* @return itemCount
* Counts how many items are in the shoppers cart
*/
public int countItems(){
int numOfItems = 0;

for(int i = 0; i < itemCount; i++){
numOfItems = numOfItems + 1;
}

return numOfItems;
}


}
}

{package jjobrien_assignement_4;

import java.util.Scanner;

import javax.swing.JOptionPane;

public class Shopper {

public final static String MENU = "\nSelect an option: \nType \"add\" to add an Item to the cart\n" +
"Type \"count\" to determine the total number of Items in the" +
"cart\n" +
"Type \"total cost\" to determine the total cost of Items in" +
"the cart\n" +
"Type \"show all\" to display the contents of the cart\n" +
"Type \"show average cost\" to display the average price of" +
"the contents of the cart\n" +
"Type \"cheapest\" to display the Item with the lowest price" +
"in the cart\n" +
"Type \"highest\" to display the Item with the highest price" +
"in the cart\n" +
"Type \"remove\" to remove a specific Item from the cart\n" +
"Type \"clear\" to remove all Items from the cart\n" +
"Type \"quit\" to exit the program: ";

public static void main (String [] args){

Scanner keyboard = new Scanner(System.in);

/*
cart[0] = new Item("Milk", 3.00);
cart[1] = new Item("Eggs", 4.25);
cart[2] = new Item("Bread", 2.50);
*/

boolean cleared = false;
boolean done = false;

double totalCartCost = 0.0;

String userName = "";

String userOption = "No option yet";

JOptionPane.showMessageDialog(null, "Welcome to the shopping cart!");

userName = JOptionPane.showInputDialog(null, "Please enter your name: ");



ShoppingCart newCart = new ShoppingCart(userName);
//While to display menu to customer and call methods based on user input
while(!done){

userOption = JOptionPane.showInputDialog(null, MENU);

if(userOption.equals("quit")){
if(quit(done) == true){
JOptionPane.showMessageDialog(null, "Thank you for using the Shopping Cart program!\n");
done = true;
}else if(quit(done) == false){
done = false;
}
}else if(userOption.equals("add")){
addItem(keyboard, newCart);
}else if(userOption.equals("count")){

}else if(userOption.equals("total cost")){
findTotalCost(newCart);
}else if(userOption.equals("show all")){
showAllItems(newCart);
}else if(userOption.equals("show average cost")){
showAverage(newCart);
}else if(userOption.equals("cheapest")){
//getCheapest();
}else if(userOption.equals("highest")){
//getHighest();
}else if(userOption.equals("remove")){
//remove();
}else if(userOption.equals("clear")){
clear(cleared, newCart);
}
}

}
/**
* Exits the program
*/

public static boolean quit(boolean isDone){
isDone = true;
return isDone;
}
/**
* Calls shopping cart class to add a single item to the array
* @param keyboard
* @param theCart
*/

public static void addItem(Scanner keyboard, ShoppingCart theCart){
String theItem = "";
String tempPrice = "";
Double thePrice = 0.0;

Item temp = null;

theItem = JOptionPane.showInputDialog(null, "Enter product name: ");
tempPrice = JOptionPane.showInputDialog(null, "Enter the price of " + theItem + ": ");
thePrice = Double.parseDouble(tempPrice);
temp = new Item(theItem, thePrice);

if(temp != null){
theCart.addItem(temp);
}

}
/**
* Will call ShoppingCart Clear Method
* @param cleared
* @param theCart
* @return
*/

public static boolean clear(boolean cleared, ShoppingCart theCart){

theCart.clear(cleared);
JOptionPane.showMessageDialog(null, "Your cart was cleared");
return cleared;
}
/**
* will call totalCost method from shopping cart class
* to add the total cost of all items stored in cart[]
* @param theCart
*/

public static void findTotalCost( ShoppingCart theCart){
double totalCost = 0;
JOptionPane.showMessageDialog(null, "Total cost: "
+ theCart.totalCost(totalCost));
}

/**
* Will print every item with their corresponding price
* in the cart[] array
*/
public static void showAllItems(ShoppingCart theCart){
String all = "";
JOptionPane.showMessageDialog(null, theCart.showAll(all));

}
/**
* calls shopping cart class to get average cost or all items
* in the current cart
*/
public static void showAverage(ShoppingCart theCart){
JOptionPane.showMessageDialog(null, theCart.showAverageCost());
}




}

}

{package jjobrien_assignement_4;

public class Item {

private static String productName;

private static double price;

public Item(){
productName = "No Name yet";
price = 0;
}

public Item(String aProductName, double aPrice){
setProductName(aProductName);
setPrice(aPrice);
}

public double getPrice(){
return price;
}

public String getProductName(){
return productName;
}

public double setPrice(double aPrice){
price = aPrice;
return aPrice;
}

public String setProductName(String aProductName){
productName = aProductName;
return aProductName;
}

public java.lang.String toString(){
String text = "";

text += productName.toString();

return text;
}

}
}

Answer

Your Item class uses static variables to store its values.

A static variable is class-level - there is only one instance of that variable which is shared by every instance of your class.

When you change the values of your Item (such as when creating a new Item), you are in fact changing the static variables - effectively setting your new values for all Item objects.

Replacing your static variables with standard member variables should resolve your issues:

private String productName;

private double price;

Note that Eclipse will automatically generate constructors and setters using the syntax:

public void setSomething(String something) {
    this.something = something;
}

and Eclipse should also give you a warning if you attempt to assign to a static variable in this way (because you are using a static variable in a non-static context.)

I'm not sure about other IDEs - but they should do something similar.

Comments