【问题标题】:How to create a method to return the number of drinks of each product using an arraylist?如何使用arraylist创建一个方法来返回每个产品的饮料数量?
【发布时间】: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


【解决方案1】:

我认为这可能会有所帮助。试试这个,看看你得到了什么。实现为 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;
}

【讨论】:

  • 非常感谢!真的很有帮助!!
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 2016-04-05
相关资源
最近更新 更多