2017-05-08 56 views
0

我有這個當前類包含所有這些成分,我試圖添加到另一個鏈表中,但我掙扎着。LinkedList中的特定元素從一個類到另一個

import java.util.*; 
public class Kitchen { 
    public static final Category CRUST = new Category("crust", 1, 1); 
    public static final Category SAUCE = new Category("sauce", 1, 1); 
    public static final Category TOPPING = new Category("topping", 2, 3); 
    private Category[] categories = { CRUST, SAUCE, TOPPING }; 
    private LinkedList<Ingredient> ingredients = new LinkedList<Ingredient>(); 

    public Kitchen() { 
     ingredients.add (new Ingredient("Thin", 3.00, CRUST)); 
     ingredients.add (new Ingredient("Thick", 3.50, CRUST)); 
     ingredients.add (new Ingredient("Tomato", 1.00, SAUCE)); 
     ingredients.add (new Ingredient("Barbeque", 1.00, SAUCE)); 
     ingredients.add (new Ingredient("Capsicum", 0.50, TOPPING)); 
     ingredients.add (new Ingredient("Olives", 1.50, TOPPING)); 
     ingredients.add (new Ingredient("Jalapenos", 1.00, TOPPING)); 
     ingredients.add (new Ingredient("Beef", 2.75, TOPPING)); 
     ingredients.add (new Ingredient("Pepperoni", 2.50, TOPPING)); 
    } 

這是包含所有成分的類,這是我試圖複製一些成分的類。

import java.util.*; 
import java.text.*; 

public class Pizza { 
    private LinkedList<Ingredient> ingredients = new LinkedList<Ingredient>(); 
    private int sold; 

    public void add(){ 
     ... 
     ... 
      if (...); 
       ingredients.add(...); 
     ... 
    } 

我應該如何去從廚房添加特定成分到比薩成分(不只是克隆整個東西:))?我嘗試過添加配料本身,但似乎並不奏效。 (inredients.add(成分))

回答

0

您可以使用枚舉而不是LinkedList來存儲所有的成分。在課堂廚房添加一個成分的枚舉。

public enum Ingredient { 
    THIN("Thin", 3.00, CRUST), 
    THICK("Thick", 3.50, CRUST); 
    // add other ingredient 
    private String name; 
    private double cost; 
    private Category category; 

    private Ingredient(String name, double cost, Category category) { 
     this.name = name; 
     this.cost = cost; 
     this.category = category; 
    } 
} 

然後在班比薩。

public void add() { 
    ingredients.add(Ingredient.THICK); 
    // add other ingredient needed 
} 
0

您可以添加getIngredients()方法將Kitchen類返回由廚房提供的成分。這允許您訪問Pizza類(和其他類)中的Kitchen的成分。

相關問題