自動裝箱與 foreach
在這個練習中,你會練習自動裝箱,以及如何迴圈走訪一個 List——這裡使用的是價格的 LinkedList。你將把一些 double 值加入 LinkedList,讓自動裝箱將它們轉成 Double,並使用「foreach」迴圈計算已為你匯入的 LinkedList 中各項目的平均價格。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 建立一個新的
Double型別的LinkedList,並將變數prices指向它。 - 在
prices清單尾端加入一個新的價格(double)9.65。在加入前,自動裝箱會自動把double轉為Double。 - 在
prices清單開頭加入一個新的價格(double)1.35。在加入前,自動裝箱會自動把double轉為Double。 - 使用「foreach」迴圈走訪並加總所有價格。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Averaging {
public static void main(String[] args) {
// Create a LinkList of Doubles using parameterized constructor
____<____> prices = ____ ____<____>();
prices.add(5.60);
// Add 9.65 to the end of the list
prices.____(____);
prices.add(3.40);
// Add 1.35 to the start of the list
prices.____(____);
System.out.println(prices);
Double total = 0.0;
// Use for each to loop through all the prices
____ (____ price : ____) {
total += price;
}
System.out.println("Average price: " + total/prices.size());
}
}