如何为arraylist项目分配权重值? java的

时间:2016-06-08 21:44:53

标签: java arraylist

我有一个arraylist,我想为每个arraylist项目分配重量值然后总结他们的重量,如牛奶重量是5糖重量是3,依此类推。 那么返回这些权重总和的公式是什么?

List<Ingredient> ing = new ArrayList<Ingredient>();



public class Ingredient {

    private String name;
    private String quantity;

  public  Ingredient(){

    }

    public Ingredient(String name,String quantity){
        this.name=name;
        this.quantity=quantity;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }


}

2 个答案:

答案 0 :(得分:1)

首先,您需要为您的Ingredient类创建一个称为weight的字段。与您对数量所做的相似。

private int weight;

public Ingredient(String name,String quantity,int weight){
        this.name=name;
        this.quantity=quantity;
        this.weight = weight;
    }

public int getWeight() {
        return weight;
    }

public void setWeight(int weight) {
        this.weight = weight;
    }

我假设您将通过构造函数设置它。 总结它们只是在列表中循环:

int sum = 0;  
for( Ingredient i : ing){
    sum+=i.getWeight();
}

答案 1 :(得分:0)

你想创建一个成分的ArrayList吗?如果是,那么您最好在Main类中创建一个单独的方法来处理总重量的计算。请参阅以下代码:

public class Main {
    private static int totalWeight(ArrayList<Ingredient> list) {
        int sum = 0;
        for (Ingredient i : list) {
            sum += i.getWeight();
        }
        return sum;
    }

    public static void main(String[] args) {
        ArrayList<Ingredient> list = new ArrayList<>();
        Ingredient a = new Ingredient("Onion", 2, 1);
        Ingredient b = new Ingredient("Potatoes", 3, 2);
        list.add(a);
        list.add(b);
        int totalWeightOfAllProducts = totalWeight(list);
        System.out.println(totalWeightOfAllProducts);
    }
}

不要忘记在您的成分类中添加重量属性!