将新Object添加到数组时,对象将被覆盖

时间:2016-10-12 16:05:38

标签: java arrays object

我正在为学校做作业,无法弄清楚为什么我的物品被我的购物车课程覆盖了。如果由我决定使用arraylist,但是赋值需要一个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;
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您的Item类使用静态变量来存储其值。

静态变量是类级别 - 该变量只有一个实例,它由类的每个实例共享。

当您更改项目的值时(例如创建新项目时),您实际上正在更改静态变量 - 有效地为所有Item对象设置新值。

用标准成员变量替换静态变量应解决您的问题:

private String productName;

private double price;

请注意,Eclipse将使用以下语法自动生成构造函数和setter:

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

如果您尝试以这种方式分配静态变量,Eclipse也应该给出警告(因为您在非静态上下文中使用静态变量。)

我不确定其他IDE - 但他们应该做类似的事情。