第2版(較早的企業之一)的「totalSale」
public static int[] totalSale(int[] mac, int[] iphone, int[] ipad, int[] ipod){
不是最佳,但它是正確的。它會打印出正確的值。
嘗試一下here。
的輸出是:
總銷售爲0類別:$ 34500
總銷售1類別:$ 9500
總銷售2類:$四百三萬一千七
總銷售3類:$ 25920
考慮使用Map
。下面是使用 '地圖' 的implmentation:
import java.util.HashMap;
import java.util.Map;
public class Test{
public static void main(String[] arguments) {
//map category to sales values
Map<String, int[]> salesMap = new HashMap<>();
//map category to sales totals
Map<String, Integer> totalSalesMap = new HashMap<>();
int[] mac = {11500,9000,13000,900,100};//total 34500
salesMap.put("Mac",mac);
int[] iphone = {1100,5000,3400,0,0};//total $9500
salesMap.put("Iphone",iphone);
int[] ipad = {900,4300000,0,800,0};
salesMap.put("Ipad",ipad);
int[] ipod = {0,300,120,500,25000};
salesMap.put("Ipod",ipod);
totalSalesMap = totalSale(salesMap);
//print totals:
for(String category : totalSalesMap.keySet()){
System.out.println("Total sale for category "
+ category + ": $" + totalSalesMap.get(category));
}
}
public static Map<String, Integer> totalSale(Map<String, int[]> salesMap){
//returned map holding sales totals
Map<String, Integer> totalSalesMap = new HashMap<>();
//iterate over sales map and sum values into totalSalesMap
for(String category : salesMap.keySet()){
int[] sales = salesMap.get(category);
int salesSum = sumArray(sales);
//add total to returned map
totalSalesMap.put(category, salesSum);
}
return totalSalesMap;
}
private static int sumArray(int[] array) {
int sum = 0;
for(int i : array) {
sum += i;
}
return sum;
}
}
你似乎是假設所有的數組'INT [] MAC,INT [] iphone,INT [] iPad上,INT [] ipod'具有相同的長度。是這樣嗎?他們代表什麼? – Alain
@ lain對不起。我添加了示例輸入值。但是陣列應該代表列出的日期的成本列表 – SSW
當您運行第一個版本時會得到什麼錯誤? – Alain