【问题标题】:how to assign weight value to arraylist items? java如何为数组列表项分配权重值?爪哇
【发布时间】:2016-06-08 21:44:52
【问题描述】:

我有一个数组列表,我想为每个数组列表项分配权重值,然后总结它们的权重,例如牛奶重量是 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;
    }


}

【问题讨论】:

  • 这不清楚 - “公式”实际上只是总和。
  • 我不知道如何处理体重值你能给我建议吗? @OliverCharlesworth
  • 为什么不在Ingredient 中添加一个weight 字段,然后在计算总重量时使用它?

标签: java arraylist


【解决方案1】:

首先,您需要为您的成分类创建一个名为 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();
}

【讨论】:

  • 恐怕数量重量;)无论如何,对于糖。对于牛奶,您可以猜测它的体积,但通常糖以重量计量。这个问题很不清楚。
  • 呵呵,好吧,那你就不用再修改类了。现在工作吗?
  • 感谢limbo,但我想根据成分重量搜索食谱\for (Recipe rn : list) { boolean recipeMatched = false; for (ShoppingList r : shop) { for (int i = 0; i &lt; rn.getIngre().size(); i++) { if (rn.getIng(i).contains(r.getName())) { matchedItems++; int temp = matchedItems; if(temp &gt;= 2){ result.add(rn);
  • 您可以将此代码添加到问题中吗?我不确定我是否明白你想要什么。
  • 我想根据成分重量搜索配方,哪个配方具有更高的建议给用户的重量值(stackoverflow.com/questions/37575625/...)请转到此链接并查看我的配方搜索方法和食谱类@limbo
【解决方案2】:

您要创建成分的 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);
    }
}

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

【讨论】:

  • 我想根据成分重量搜索食谱,哪个食谱具有更高的建议给用户的重量值(stackoverflow.com/questions/37575625/…)请转到此链接查看我的食谱搜索方法和食谱类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多