LoslegenKostenlos loslegen

Autoboxing and foreach

In this exercise, you will explore autoboxing and looping of a List - specifically a LinkedList of prices. You will add some double to the LinkedList and allow autoboxing to convert them to Double, and use the "foreach" loop to get the average price of the prices in the LinkedList.

Diese Übung ist Teil des Kurses

Data Types and Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • Construct a new LinkedList of Doubles and set the prices variable to it.
  • Add a new price (a double) 9.65 to the end of the prices list. Autoboxing will automatically convert the double to a Double before adding it.
  • Add a new price (a double) 1.35 to the beginning of the prices list. Autoboxing will automatically convert the double to a Double before adding it.
  • Use a "foreach" loop to iterate through and sum all prices.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

import java.util.LinkedList;

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());
	}
}
Code bearbeiten und ausführen