I'm not sure how to formulate the question but say I have a pizza with toppings, and I want (through the main class) to print or call to the description of this pizza that contains not one but two toppings, how should I do this?
My toppings class is an enum so I've tried, so far, this:
public class Pizza{
private Toppings[] toppings;
public Pizza(Toppings[] toppings){
this.toppings = new Toppings[]{Toppings.tomatosauce, Toppings.cheese};
}
public String toString(){
return "Toppings: " toppings;
}
}
then in the main class:
public class Main {
public static void main(String[] args) {
Pizza pizza = new Pizza(Toppings.cheese);
System.out.println(pizza);
}
}
Obviously, this is wrong, as it only prints the cheese topping. Any hints?
CodePudding user response:
You can use this:
public class Pizza{
private Toppings[] toppings;
public Pizza(Toppings ...toppings){
this.toppings = toppings;
}
public String toString(){
return "Toppings: " Arrays.toString(toppings);
}
}
class Main {
public static void main(String[] args) {
Pizza pizza = new Pizza(Toppings.cheese, Toppings.tomato);
System.out.println(pizza);
}
}
enum Toppings { cheese, tomato }
or
Pizza pizza = new Pizza(new Toppings[]{Toppings.cheese, Toppings.tomato});
instead and change the constructor of Pizza
:
public Pizza(Toppings[] topping) {
...
}