【发布时间】:2017-04-28 00:13:33
【问题描述】:
我是初学者,我不知道如何访问我建立的数组列表以返回每种产品的饮料数量(例如 4 可乐)
附:该产品是我其他班级的名称。
到目前为止,这是我的代码:
import java.util.ArrayList;
public class VendingMachine {
ArrayList <Product> vending = new ArrayList <Product> ();
public VendingMachine(int maxType, int quantity) {
int maxCap= maxType*quantity;
vending = new ArrayList <Product> (maxCap);
}
//Initialize the number & quantity of the products
public ArrayList <Product> initialize () {
for (int i=0; i<6; i++) {
Product coke = new Product("Coke", 1.30, 230, 350, false);
vending.add(coke);
}
for (int i=0; i<6; i++) {
Product pepsi = new Product("Pepsi", 1.10, 240, 350, false);
vending.add(pepsi);
}
for (int i=0; i<6; i++) {
Product gingerAle = new Product("GingerAle", 1.30, 210, 320, false);
vending.add(gingerAle);
}
for (int i=0; i<6; i++) {
Product dietCoke = new Product("DietCoke", 1.50, 200, 310, true);
vending.add(dietCoke);
}
for (int i=0; i<6; i++) {
Product dietPepsi = new Product("DietPepsi", 1.40, 190, 320, true);
vending.add(dietPepsi);
}
return vending;
}
【问题讨论】:
-
我对 Java 不太熟悉,但 ArrayList 不是 VendingMachine 类的一部分吗?如果是这样,您不能遍历 VendingMachine.vending 并计算产品名称的数量吗?就像一个遍历每个产品并根据某个参数检查 product.name 的 for 循环,如果它是真的,它会增加一些计数器?
-
感谢您的评论!我已经尝试过了,但它一直向我显示错误并且不允许我使用迭代。
-
你能告诉我们你的迭代代码吗?
-
Product类是什么?它应该有一个“数量”字段,而不是只为每个相同的产品创建多个实例吗?
标签: java sorting object arraylist