簡體   English   中英

將數組中的元素添加在一起時遇到麻煩

[英]Having trouble adding together elements from array

我必須編寫一個使用兩個類創建購物清單的程序。 第一類創建一個數組來保存從第二類獲得的值。 該數組包含具有名稱,數量和價格值的雜貨項目。 我有一個應該獲取數組中所有內容總成本的函數,但是由於某種原因,該函數只是將添加到數組中的最后一項添加到自身中。 這是我的代碼:

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循環,該循環將一次在數組中運行一個元素,並將存儲在該元素中的所有值存儲到一個新對象中。 我感覺自己朝着正確的方向前進,但無法弄清楚該功能的問題所在。 誰能看到我的問題所在,或者至少給我一些有關如何開始嘗試解決問題的建議?

如果您想在雜貨店中添加一些品種,則quantitypricePerUnit的靜態修飾符沒有任何意義。 發生的情況是,每次調用構造函數或GroceryItemOrder時,都會更改這兩個靜態字段,因此,如果這會影響以前創建的所有訂單的總價。 其余的都很好,即使有時可能更簡潔。

GroceryItemOrder中3個變量中的GroceryItemOrderstatic ,這意味着整個類只有一個變量,而不是每個實例一個。 每個新實例都會覆蓋先前創建的實例設置的值。

使所有這些實例變量不是static

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM