繁体   English   中英

返回 java 中两个自定义类型列表的所有可能组合

[英]Return all possible combinations of two custom type lists in java

我正在尝试将配料的值和配料添加到我的勺子列表中,但由于勺子的类型,这不起作用。 我无法将勺子的类型更改为字符串,我需要解决问题,因为它在下面的代码中。 查看图片以查看我在尝试向列表中添加值时遇到的问题。

import java.util.ArrayList;
import java.util.List;

import static java.lang.Math.abs;

public class IceCreamMachine {
    public String[] ingredients;
    public String[] toppings;

    public static class IceCream {
        public String ingredient;
        public String topping;

        public IceCream(String ingredient, String topping) {
            this.ingredient = ingredient;
            this.topping = topping;
        }
    }

    public IceCreamMachine(String[] ingredeints, String[] toppings) {
        this.ingredients = ingredeints;
        this.toppings = toppings;
    }

    public List<IceCream> scoops() {
        List<IceCream> scoops = new ArrayList<>();
        
        for (int j = 0; j<ingredients.length;j++){
            for(int l = 0; l<toppings.length;l++){
                scoops.add(ingredients[j]+", "+toppings[l]);
            }
        }
        return scoops;
    }

    public static void main(String[] args) {
        IceCreamMachine machine = new IceCreamMachine(new String[]{
                "vanilla", "chocolate"
        }, new String[]{
                "chocolate sauce"
        });
        List<IceCream> scoops = machine.scoops();

        /*
         * Should print:
         * vanilla, chocolate sauce
         * chocolate, chocolate sauce
         */
        for (IceCream iceCream : scoops) {
            System.out.println(iceCream.ingredient + ", " + iceCream.topping);
        }
    }
}

你很亲密。 一行要改。

scoops.add(new IceCream(ingredients[j],toppings[l]));

代替

scoops.add(ingredients[j]+", "+toppings[l]);

你需要一个“完整的”冰淇淋IceCream来添加到scoops object 中。 但是您的代码将描述构造为String

我很困惑。

首先,您可以轻松编写 for,如下所示:

for(String ingredient:ingredients) 
   for (String topping:toppings)
      scoops.add(new IceCream(ingredient, topping));

我看到的问题是您试图在list<IceCream>中添加一个String 两者不兼容,它甚至不应该编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM