2014-10-18 50 views
3

我基本上需要一套添加到我已經允許「客戶」添加或刪除配料一旦創建比薩餅。這裏是我已經有:披薩類。添加一個名爲setOfToppings的集合作爲屬性。使用Java

package pizza; 

public class Pizza { 

// Declare enums 
public enum Size{ 
    SMALL, 
    MEDIUM, 
    LARGE, 
    JUMBO 
} 

public enum Crust{ 
    CHEESY, 
    HAND_TOSSEDS, 
    THIN_AND_CRISPY, 
    DEEP_PAN 
} 

public enum Topping{ 
    MUSHROOMS, 
    GREEN_PEPPERS, 
    HAM, 
    PEPPERONI, 
    SAUGSAGE 
} 


// declare variables 
private Size pizzaSize; 
private Crust crustType; 

private Set<Topping> setOfToppings = new EnumSet<Topping>(Topping.class); 

public Pizza(){ 

} 

public Pizza(Size pizzaSize, Crust crustType) { 
    this.pizzaSize = pizzaSize; 
    this.crustType = crustType; 
} 

public Size getPizzaSize() { 
    return pizzaSize; 
} 
public void setPizzaSize(Size pizzaSize) { 
    this.pizzaSize = pizzaSize; 
} 
public Crust getCrustType() { 
    return crustType; 
} 
public void setCrustType(Crust crustType) { 
    this.crustType = crustType; 
} 

public String toString(){ 
    return "A "+pizzaSize+" Pizza with "+crustType+" crust" + "with topping: " + setOfToppings; 
} 


} 

這裏是測試代碼:

package pizza; 
import pizza.Pizza.Crust; 
import pizza.Pizza.Size; 

public class PizzaTest { 

public static void main(String[] args) { 

// use constructor 1 
    Pizza vegieCrunch = new Pizza(); 
    vegieCrunch.setCrustType(Crust.THIN_AND_CRISPY); 
    vegieCrunch.setPizzaSize(Size.MEDIUM); 

// constructor 2 
    Pizza doubleCheese = new Pizza(Size.LARGE, Crust.CHEESY); 

    Pizza PartyPizza = new Pizza(Size.JUMBO, Crust.DEEP_PAN); 

    // use of getters 
    System.out.println("Pizza Vegie Crunch::"); 
    System.out.println("Size: "+vegieCrunch.getPizzaSize()); 
    System.out.println("Crust Type: "+vegieCrunch.getCrustType()); 

    // use of toString 
    System.out.println("\nPizza Double Cheese:"); 
    System.out.println(doubleCheese.toString()); 

    System.out.println("\nPizza Country Feast:"); 
    System.out.println(PartyPizza.toString()); 

    } 

    } 

當前的代碼,我有偉大工程,我只需要增加一個額外的枚舉澆頭幫助,並添加一組命名爲setOfToppings,這樣當我測試它時,'客戶'可以在創建比薩後添加或刪除澆頭。預先感謝您,我對Java比較陌生,所以任何提示或建議也歡迎!

回答

1

[...]我只需要增加一個額外的枚舉Toppings

用同樣的方法,你定義你的其他枚舉幫助:

public enum Topping { 
    PINEAPPLE, 
    BANANA 
} 

[...]並添加一組名爲setOfToppings

然後添加一個字段:

private Set<Topping> setOfToppings = EnumSet.noneOf(Topping.class); 

您可以創建訪問方法,比如

public void addTopping(Topping topping) { 
    setOfToppings.add(topping); 
} 

public Set<Topping> getToppings() { 
    return setOfToppings; 
} 

public void addManyToppings(Topping... toppings) { 
    setOfToppings.addAll(Arrays.asList(toppings)); 
} 
+0

我得到一個錯誤,當我添加字段:私訂 setOfToppings =新EnumSet (Topping.class);說下列:不能實例化類型EnumSet InNeedOfHelp 2014-10-18 20:19:57

+0

對不起。答案已更新。 – aioobe 2014-10-18 20:22:28

+0

另外我應該如何將Toppings添加到測試部分?並感謝您的幫助! – InNeedOfHelp 2014-10-18 20:23:12

相關問題