无法从数组中添加元素

时间:2014-09-05 22:19:52

标签: java arrays function

我必须编写一个程序,它使用两个类来创建一个购物清单。第一个类创建一个数组来保存从第二个类获得的值。该数组包含具有名称,数量和价格值的杂货。我有一个函数应该得到数组中所有内容的总成本,但由于某种原因,该函数只是将添加到数组中的最后一项添加到自身。这是我的代码:

public class GroceryList {

private GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
private int numofEntries;

public GroceryList()
{
    this.groceryList = new GroceryItemOrder[10];
    this.numofEntries = 0;
}

public void add(GroceryItemOrder item)
{
    if(numofEntries == 10)
    {
        System.out.println("The list is full.");
    }
    else
    {
        groceryList[numofEntries] = item;
        numofEntries++;
    }

}

public double getTotalCost()
{
    double totalCost = 0;
    double newCost = 0;

    for(int size = 0; size < numofEntries; size ++)
    {
        newCost = groceryList[size].getCost();
        totalCost = newCost + totalCost;
    }

    return totalCost;


}



public class GroceryItemOrder {

private static double pricePerUnit;
private static int quantity;
private String name;

public GroceryItemOrder(String name, int quantity, double pricePerUnit)
{
    this.name = name;
    this.quantity = quantity;
    this.pricePerUnit = pricePerUnit;
}


public static double getCost()
{
    return (quantity * pricePerUnit);
}

public void setQuantity(int quantity)
{
    this.quantity = quantity;
}


public static void main(String[] args)
{
    GroceryList newList = new GroceryList();

    newList.add(new GroceryItemOrder("cookies", 1, 1.50));
    newList.add(new GroceryItemOrder("cheese", 2, 1.0));
    newList.add(new GroceryItemOrder("bread", 1, 5.0));

    System.out.println(newList.getTotalCost());

}
}

在函数中,我试图使用一个for循环,它一次遍历数组一个元素,并将存储到元素中的任何值存储到一个新对象中。我觉得我正朝着正确的方向前进,但无法弄清楚问题在哪里。任何人都可以看到我的问题所在,或者至少就如何开始尝试解决问题给我一些建议?

2 个答案:

答案 0 :(得分:0)

quantitypricePerUnit的静态修饰符没有任何意义,如果你想要在你的杂货店有一些变化。会发生的是每次调用构造函数或GroceryItemOrder时,都会更改这两个静态字段,因此会影响所有先前创建的订单的总价。其余的都很好,即使它有时可能更简洁。

答案 1 :(得分:0)

GroceryItemOrder中3个变量中的2个是static,这意味着整个类只有一个变量,而不是每个实例都有一个变量。每个新实例都会覆盖先前创建的实例设置的值。

使所有这些实例变量不是static

private double pricePerUnit;
private int quantity;
private String name;