如何访问此数组的itemPrice部分?

时间:2017-02-23 00:52:42

标签: java arrays

所以我需要获取索引的itemPrice部分并将它们全部添加在一起,但我不确定如何访问它。我可以以某种方式使用GroceryItemOrder类中的getCost方法并将其连续添加到GroceryList类中的totalCost,或者我是否需要访问每个存储对象的itemPrice和quantity部分。

public class GroceryList {

    public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
    public int manyItems;


    public GroceryList() {
        final int  INITIAL_CAPACITY = 10;
        groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
        manyItems = 0;
    }

    //Constructs a new empty grocery list array
    public GroceryList(int numItem) {
        if (numItem < 0)
            throw new IllegalArgumentException
                    ("The amount of items you wanted to add your grocery list is negative: " + numItem);
        groceryList = new GroceryItemOrder[numItem];
        manyItems = 0;
    }

    public void add(GroceryItemOrder item) {
        if (manyItems <= 10) {
            groceryList[manyItems] = item;
        }
        manyItems++;
    }

    //
    // @return the total sum list of all grocery items in the list
    public double getTotalCost() {
        double totalCost = 0;
        for (int i = 0; i < groceryList.length; i++ ) {
            //THIS PART
        }
        return totalCost;
    }

}

这是GroceryItemOrder

public class GroceryItemOrder {
    public String itemName;
    public int itemQuantity;
    public double itemPrice;

    public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
        itemName = name;
        itemQuantity = quantity;
        itemPrice = pricePerUnit;
    }

    public double getcost() {
        return (itemPrice*itemQuantity);
    }

    public void setQuantity(int quantity) {
        itemQuantity = quantity;
    }

    public String toString() {
        return (itemName + " " + itemQuantity);
    }

}

感谢所有回复!我让它运转起来,明白现在发生了什么。

2 个答案:

答案 0 :(得分:1)

您首先需要访问数组中的GroceryItemOrder实例,然后从那里访问其itemPrice字段,

groceryList[0].itemPrice

将为您提供groceryList数组中第一个groceryListOrder的itemPrice。如果您想使用方法来执行此操作,请在getItemPrice类中添加groceryListOrder方法,

public getItemPrice() {
    return itemPrice;
}

然后你可以像这样访问数组中的每个groceryListOrder的itemPrice,

groceryList[0].getItemPrice()

groceryList[0].itemPrice相同。如果您想获得groceryList数组中所有对象的总费用,请使用循环添加所有itemPrice字段乘以itemQuantity字段(因为它是&#39; s使用getcost方法

将每个对象的总成本汇总在一起
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
    totalCost += groceryList[i].getcost();
}

答案 1 :(得分:0)

这对我有用,您还需要设置static GroceryItemOrder[] groceryList = new GroceryItemOrder[0];

//
// @return the total sum list of all grocery items in the list
public static double getTotalCost() {
    double totalCost = 0;
    for (int i = 0; i < groceryList.length; i++ )
    {
        totalCost += groceryList[i].getcost();
    }
    return totalCost;
}