2013-10-04 97 views
-3

由於我是一名初學者,請我正在用JAVA掙扎。我應該做的是:計算和打印項目總數的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 
+0

還有,你試過嗎? –

+0

您的輸出看起來與您發佈的代碼不匹配。爲什麼這樣?! – SudoRahul

+2

當我們開始得到這些問題時,我一定需要啤酒:P – MadProgrammer

回答

2

for-loop開頭,每個項目打電話getCost,打印結果。

public static void printOrderCost(Beer[] order) { 
    double totalCost = 0; 
    int count = order.length; 
    for (Beer beer : order) { 
     // Use beer.getCost() and add it to the totalCost 
    } 
    // Print the results... 
} 

看看The for statement更多細節

+0

'int count = order.length;'真的需要嗎? #JustCurious :) – SudoRahul

+0

@RJ不,也可能會導致'NullPointerException',但它似乎是一個要求,所以我填充了它......「你有n啤酒@總成本$ xxxx」.. .. – MadProgrammer

+0

@RJ最終結果'10啤酒成本是111億美元':),其中10是數。 –