Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return all possible combinations of two custom type lists in java

I am trying to add the values of ingredients and topping to my scoops list, but that doesn’t work due to the type of scoops. I can’t change the type of scoops to String and I need to solve the problem as it is in the code below.
See the picture to see the problem I get when I try to add values to the list.

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are very close. One line to change.

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

instead of

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

You need a ‘full’ IceCream object to add to the scoops object.
But your code constructed a description as a String.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading