我的枚举代码如下:
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;
}
}
}
这是我创建咖啡的代码:
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();
}
}
我得到的错误就在行中:
咖啡c1 =新咖啡(成分,类型.FLAT_WHITE);
构造函数Coffee(ArrayList,CoffeeFactory.Type)未定义。有人可以解释并告诉我我做错了什么,或者我是否误解了什么。
答案 0 :(得分:0)
该行
Coffee c1 = new Coffee(ingredients, type.FLAT_WHITE);
应该以下:
Coffee c1 = new Coffee(ingredients, type);
Coffee c1 = new Coffee(ingredients, Type.FLAT_WHITE);
你可能想要第一个。变量type
已包含对Type
枚举实例FLAT_WHITE
的引用。你知道这一点,因为你在switch
的那个分支。
答案 1 :(得分:0)
这没有错。
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;
}