對于我目前的任務,我必須創建一個程式來制作比薩餅、選擇配料、計算訂單總額并將訂單匯出到 txt 檔案。所有這些都是在帶有多個控制器類的 JavaFX 中完成的。
package application;
import java.util.ArrayList;
// You can add additional methods for help.
public abstract class Pizza // Abstract is used to make specific methods that will be used by other classes that are related to pizza.
{
protected ArrayList<Topping> toppings = new ArrayList<Topping>(); // How the heck do I use this???
protected Size size; // Enum Class
public abstract double price();
}
上面的代碼是我的披薩課。我必須使用包含的引數,但如果需要,我可以添加更多方法。我遇到的問題是使用 ArrayList,它必須具有“Topping”專案集合。這是我們第一次使用 ArrayList(他們從來沒有教過我們如何正確使用它,這真的很糟糕)所以我用澆頭串列創建了一個列舉類。
package application;
public enum Topping
{
Pepperoni, Sausage, Chicken, Beef, Ham, GreenPepper, Onion, Mushroom, Pinapple, BlackOlives;
}
但現在我不知道我應該如何使用 ArrayList。例如,對于特定型別的比薩(豪華、夏威夷、意大利辣香腸),我的比薩類有繼承類。下面的代碼是它現在的樣子的一個例子。我想要豪華比薩餅的配料是雞肉、蘑菇、青椒、香腸和洋蔥。然后用戶將能夠在主程式中添加或洗掉澆頭。
package application;
public class PizzaDeluxe extends Pizza
{
@Override
public double price()
{
return 0;
}
}
我如何讓豪華披薩課程從某些配料開始?在我這樣做之后,我如何才能洗掉或添加某些澆頭?最后,我將如何獲得披薩上的配料資訊串列?
uj5u.com熱心網友回復:
對于您的Pizza類,您可能想要創建addTopping和removeTopping方法。要列出所有澆頭,您可能需要創建一個 getter:
public abstract class Pizza {
protected List<Topping> toppings = new ArrayList<>();
protected Size size; // Enum Class
public abstract double price();
public void addTopping(Topping topping) {
toppings.add(topping);
}
public void removeTopping(Topping topping) {
toppings.remove(topping);
}
public List<Topping> getToppings() {
return toppings;
}
}
為了PizzaDeluxe使用某些澆頭進行初始化,我們可以在建構式中使用addAll:
public class PizzaDeluxe extends Pizza {
public PizzaDeluxe() {
toppings.addAll(Arrays.asList(Topping.Chicken, Topping.Mushroom, Topping.GreenPepper, Topping.Sausage, Topping.Onion));
}
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/351983.html
