2013-10-04 54 views
-2

我所應該做的事:調用Java中的方法和返回啤酒成本

添加一些必要的語句到printOrderCost()方法在 主類,以這種方法計算並打印的 總成本訂單中的所有啤酒項目。 (此方法調用getCost()方法 每個啤酒項,累積全部getCost() 值的總和,然後打印的總和 - 所有啤酒對象的總成本。)

代碼:

public static void printOrderCost(Beer[] order) 
{ 
    double totalCost; 
    int count; 

} 


} 

public double getCost() 
{ 
    double cost; 
    cost = quantity * itemCost; 
    return (cost); 

} 

public String toString() // not necessary to format the output 
{ 
    String s; 
    s = brand + " "; 
    s += quantity + " " ; 
    s += itemCost + " "; 
    s += getCost(); 

    return s; 


} 

輸出:

Bud 5 3.0 15.0 
Canadian 5 1.0 5.0 
Blue 3 2.0 6.0 
White Seal 4 1.0 4.0 
Bud Light 1 2.0 2.0 
+2

1),看它是否工作,編寫代碼來測試它。 2)調用'toString()'中的方法,只需調用它。讓我們看看你想出了什麼。 –

+1

不要刪除你的問題後,它已被回答... –

回答

0

您的代碼看起來好像沒什麼問題。要在toString()方法中調用getCost(),只需使用getCost()調用它即可。

所以你的toString()方法應該是這樣的:

public toString(){ 
    String s; 
    s = brand + " "; 
    s += quantity + " " ; 
    s += itemCost + " "; 
    s += getCost(); 

    return s; 
} 

希望這是你在找什麼:)

+0

奇妙,偉大的工作CodingBird,這正是我所期待的,我真的appreicate你的幫助 –

+0

使用'StringBuilder'而不是字符串,並在返回時將其轉換爲'string',這將有助於你正確的內存管理。 – Yup

0

從您提供的代碼中,getCost法「長相「精

toString方法應該只需要被附加到returnStrings

public String toString() // not necessary to format the output 
{ 
    String s; 
    s = brand + " "; 
    s += quantity + " " ; 
    s += itemCost + " "; 
    s += getCost(); 
    return s; 
} 

你可能也想看看NumberFormat,這將允許您控制輸出格式,以防萬一你得到一個好笑的看着值;)

+0

感謝MadProgrammer我感謝您的幫助 –

0

它通常是一個壞主意,添加字符串因爲Java會爲每次添加創建一個唯一的String,這會導致一些不必要的開銷。您可以使用StringBuilder作爲通用工具,或者,如果您知道字符串的確切格式,可以使用String.format(...)。

實施例:

public toString() { 
    return String.format("%-10s %2d %6.2f %6.2f", brand, quantity, itemCost, getCost()); 
}