2017-04-16 53 views
-5

所以我有一個任務,並且我已經爲它創建了大部分代碼,但我無法弄清楚如何爲澆頭添加價格。這不是我的主要代碼,這是針對比薩尺寸的價格,但我還需要在澆頭中添加更多價格。我需要添加兩個單獨的價格,一個用於中型比薩和一個用於大比薩。將價格添加到澆頭

package assignment1; 

public class Pizza { 

private int diam; 
private int numOfPizza; 
private double price; 
private String toppings; 

Pizza(int size, String input) { 
diam = size; 
toppings = input; 

} 

public int getDiameter(){ 
    return diam; 
} 
public int getPizzaCount(){ 
    return numOfPizza; 
} 
public double getPrice(){ 
    return price; 
} 
public String getToppings(){ 
    return toppings; 
} 
public void setDiameter(int size){ 
if (size == 12) 
    diam = 12; 
else if (size == 16) 
    diam = 16; 
else 
    diam = 0; 
}  
public void setPizzaCount(int pizzaCount){ 
    numOfPizza = pizzaCount; 
} 
public void setPrice(double total){ 
    price = total; 
} 
public void setToppings(String input){ 
    if ("Ham".equalsIgnoreCase(input)) 
     toppings = "Ham"; 
    else if ("Mozarella".equalsIgnoreCase(input)) 
     toppings = "Mozarella" ; 
    else if ("Olives".equalsIgnoreCase(input)) 
     toppings = "Olives"; 
    else if ("Pineapple".equalsIgnoreCase(input)) 
     toppings = "Pineapple"; 
    else if ("Spinach".equalsIgnoreCase(input)) 
     toppings = "Spinach"; 
    else 
     toppings = "Plain"; 
} 
private double calculatePrice(int size, String input){ 
    int total; 
    if(!(toppings).equalsIgnoreCase("plain")) { 
     total = 1; 
    } else { 
     total = 0; 
    } 

    if(size == 12) { 
     total += 4.00; 
    } 

    else if(size == 16) { 
     total += 5.00; 
    } 

    return total; 
} 
    public String toString(){ 
     String pizzaString ="You have ordered a "+diam + " inch pizza with 
"+toppings +" toppings and a price of £"+ calculatePrice(diam, toppings); 
     return pizzaString; 
    } 
} 
+0

在'calculatePrice'中,您應該在'setToppings'方法中重複相同的'if-elseif',根據頂部名稱添加不同的價格。你也可以使用'switch',這樣讀起來更清晰一些。您也可以使用頂部名稱作爲鍵和價格作爲價值的地圖,但'switch'就好了。啊,順便說一句,它是Mo ** zz ** arella :) – BackSlash

+0

但對於本網站更重要 - 如果你發佈了一個問題,你應該詢問一個實際的問題。您剛剛發佈了代碼和廣泛的要求,並且不符合本網站的質量標準。請仔細閱讀[幫助]中的「如何提問」部分,詳細瞭解本網站的工作方式以及如何提問以獲得讚賞和答案。 –

+0

感謝您的幫助 –

回答

0

您可以創建類似的東西,將價格設置爲每個頂部。首先初始化總數,然後根據添加的澆頭增加總數。

private double calculatePrice(int size, String input){ 
int total = 0; 

if (toppings == "Ham") 
{ 
    total = total + 2; 
} 

else if (toppings == "Olives") 
{ 
    total = total + 3; 
} 

return total; 
} 
+0

這真的可以幫到我,謝謝 –

+0

不客氣! –