2016-06-08 204 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