java - 如何访问该数组的 itemPrice 部分?

标签 java arrays

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

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);
    }

}

谢谢大家的回复!我让它工作并了解现在发生了什么。

最佳答案

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

groceryList[0].itemPrice

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

public getItemPrice() {
    return itemPrice;
}

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

groceryList[0].getItemPrice()

groceryList[0].itemPrice的作用相同。如果您想获取 groceryList 数组中所有对象的总成本,请使用循环将所有 itemPrice 字段乘以 itemQuantity 相加> 字段(因为它是每个对象的总成本相加),通过使用您的 getcost 方法,

double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
    totalCost += groceryList[i].getcost();
}

关于java - 如何访问该数组的 itemPrice 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405122/

相关文章:

java - 从图库中选择的位图图像未显示在 Android 版本 5.0.2 的 imageview 中

JavaFX SplitMenuButton 设置箭头的位置

c++ - 在 C++ 中计算数组中不相等的字符串

arrays - Jade 双阵列显示

Javascript - 遍历数组并根据其中的键值对对象进行排序

java - JSP - 将变量传递给 servlet

java - 使用 JNA 启动/停止服务

java - 比较 Array Java 中的股票值(value)

Java - 泛型方法的数组参数的类型推断

java - 我在Java中使用这个方法调用时调用的方法是什么?