[英]Undefined Constructor Enum Java
我的枚舉有以下代碼:
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)是未定義的。 有人可以解釋一下,告訴我我做錯了什么,或者如果我誤解了什么。
線
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
那個分支中。
沒有錯。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.