I have the following code for my enum:
public class CoffeeFactory {
public static enum Type {
LONG_BLACK(4.0),
FLAT_WHITE(4.75),
MOCHA(5.5);
private double price;
Type(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
public static enum Ingredient {
ESPRESSO(0.5),
MILK(1),
CHOCOLATE(1.5);
private double cost;
Ingredient(double cost) {
this.cost = cost;
}
public double getCost() {
return cost;
}
}
public static Coffee CreateCoffee(Type type){
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
switch (type) {
case FLAT_WHITE:
ingredients.add(Ingredient.MILK);
Coffee c1 = new Coffee(ingredients, type.FLAT_WHITE);
return c1; //new Coffee(ingredients, Type.FLAT_WHITE);
break;
case LONG_BLACK:
ingredients.add(Ingredient.ESPRESSO);
return new Coffee(ingredients, Type.LONG_BLACK);
break;
case MOCHA:
ingredients.add(Ingredient.CHOCOLATE);
return new Coffee(ingredients, Type.MOCHA);
break;
default:
break;
}
}
}
This is my code for creating a coffee:
import patt.Coffee.CoffeeFactory.Ingredient;
public class Coffee {
Type type;
double cost;
ArrayList<Ingredient> ingredients;
public Coffee(ArrayList<Ingredient> ingredients, Type type) {
this.type = type;
this.ingredients = ingredients;
}
public double getCost() {
return cost;
}
public double getPrice() {
return type.ordinal();
}
public String listIngredients() {
return type.toString();
}
}
The error im getting is in the line:
Coffee c1 = new Coffee(ingredients, type.FLAT_WHITE);
the constructor Coffee(ArrayList, CoffeeFactory.Type) is undefined. Could someone please explain and show me what I have done wrong or if I'm misunderstanding something.
The line
Coffee c1 = new Coffee(ingredients, type.FLAT_WHITE);
should be one of the following:
Coffee c1 = new Coffee(ingredients, type);
Coffee c1 = new Coffee(ingredients, Type.FLAT_WHITE);
You probably want the first one. The variable type
already contains a reference to the Type
enum instance FLAT_WHITE
. You know this because you're in that branch of the switch
.
There is no mistake in this.
public static Coffee CreateCoffee(Type type){
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
switch (type) {
case FLAT_WHITE:
ingredients.add(Ingredient.MILK);
Coffee c1 = new Coffee(ingredients, Type.FLAT_WHITE);
return c1; //new Coffee(ingredients, Type.FLAT_WHITE);
case LONG_BLACK:
ingredients.add(Ingredient.ESPRESSO);
return new Coffee(ingredients, Type.LONG_BLACK);
case MOCHA:
ingredients.add(Ingredient.CHOCOLATE);
return new Coffee(ingredients, Type.MOCHA);
default:
break;
}
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.