Java 如何创建一个方法,使用arraylist返回每个产品的饮料数量?
我是一个初学者,我不知道如何访问我建立的arraylist,以便能够返回每种产品的饮料数量(例如4杯可乐) 另外,这个产品是我另一个班级的名字 以下是我目前的代码:Java 如何创建一个方法,使用arraylist返回每个产品的饮料数量?,java,sorting,object,arraylist,Java,Sorting,Object,Arraylist,我是一个初学者,我不知道如何访问我建立的arraylist,以便能够返回每种产品的饮料数量(例如4杯可乐) 另外,这个产品是我另一个班级的名字 以下是我目前的代码: import java.util.ArrayList; public class VendingMachine { ArrayList <Product> vending = new ArrayList <Product> (); public VendingMachine(int maxT
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;
}
import java.util.ArrayList;
公营自动售货机{
ArrayList vending=新的ArrayList();
公共自动售货机(整数最大类型,整数数量){
int maxCap=maxType*数量;
自动售货=新阵列列表(maxCap);
}
//初始化产品的数量和数量
公共ArrayList初始化(){
对于(inti=0;i我认为这可能会有所帮助。试试这个,看看你得到了什么。实现为VendingMachine类的方法
public int getProductCount(String pName) throws IllegalArgumentException {
int count = 0;
if (pName == null) {
throw new IllegalArgumentException();
}
for (Product item : this.vending) {
//Assuming the instance variable of your Product class is called name
//Also assuming name is private and you have a getter method in your Product class
if (item.getName().equalsIgnoreCase(pName)) {
count++;
}
}
return count;
}
我对Java不太熟悉,但是ArrayList vending不是VendingMachine类的一部分吗?如果是这样,您不能遍历VendingMachine.vending并计算产品名称的数量吗?就像一个for循环,它遍历每个产品并根据一些参数检查product.name,如果它是真的,它会增加一些计数器吗?谢谢您的合作提示!我已经尝试过了,但它一直向我显示错误,不允许我使用iterate。你能给我们看一下你的迭代代码吗?什么是Product
类?它应该有一个“quantity”字段,而不是只创建每个相同产品的多个实例吗?非常感谢!真的很有帮助!!