gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:00:45 25 4
gpt4 key购买 nike

所以我需要获取索引的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com