Home > Software engineering >  Return all possible combinations of two custom type lists in java
Return all possible combinations of two custom type lists in java

Time:08-26

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

CodePudding user response:

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.

CodePudding user response:

I'm perplexed.

First of all you can easily write the for as it follows:

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

The problem I see is that you are trying to add a String in a list<IceCream>; the two are not compatible, it shouldn't even compile.

  •  Tags:  
  • java
  • Related