2016-06-08 98 views
-2

我有一个arraylist,我想为每个arraylist项目分配权值,然后总结他们的权重,如牛奶重量是5糖重量是3等等。 那么什么是公式返回这些权重的总和?如何将权重值分配给数组列表项目? java

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; 
    } 


} 
+0

这并不清楚 - “公式”实际上只是总和。 –

+0

我不知道如何治疗体重值可以给我建议吗? @OliverCharlesworth – Bsm

+1

为什么不在“成分”中加一个“weight”字段,然后在计算总重量时使用它? – Jashaszun

回答

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(); 
} 
+0

恐怕数量*就是重量;反正对于糖来说。对于牛奶,你可以猜出它的体积,但通常糖的重量是衡量的。这个问题还不清楚。 – Arjan

+0

嘿嘿,好的,你不需要再修改课程了。现在工作? – limbo

+0

感谢limbo,但我想根据配料重量搜索配方\ '(配方rn:list){ 布尔recipeMatched = false;对于(int i = 0; i = 2){ result.add(rn);' – Bsm

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); 
    } 
} 

不要忘了在您的配料类中添加重量属性!

+0

我想要搜索配方基于成分重量哪个食谱具有更高的权重价值建议给用户(http://stackoverflow.com/questions/37575625/how-to-search-recipe-based-on-important-ingredients-java-android)请转到此链接并查看我的食谱搜索方法和食谱类 – Bsm