Page 450 - Introduction to Programming with Java: A Problem Solving Approach
P. 450

                416 Chapter 10 Arrays and ArrayLists
 /******************************************************************
*
StockAverage.java
Dean & Dean
This program uses an ArrayList to store user-entered stock
values. It prints the average stock value.
******************************************************************/
*
*
*
*
import java.util.Scanner;
import java.util.ArrayList;
public class StockAverage
{
  public static void main(String[] args)
 {
Scanner stdIn = new Scanner(System.in);
ArrayList<Double> stocks = new ArrayList<Double>();
double stock;
double stockSum = 0;
// a stock value
// sum of stock values
System.out.print("Enter a stock value (-1 to quit): ");
stock = stdIn.nextDouble();
 while
(stock
>= A0)pago PDF Enhancer Autoboxing takes place here.
   {
stocks.add(stock);
System.out.print("Enter a stock value (-1 to quit): ");
stock = stdIn.nextDouble();
// end while
for (int i=0; i<stocks.size(); i++)
}
{
    }
// end class StockAverage
}
// end main
}
stock = stocks.get(i);
stockSum += stock;
Unboxing takes place here.
if (stocks.size() != 0)
{
}
System.out.printf("\nAverage stock value = $%.2f\n",
stockSum / stocks.size());
This must be a wrapper class, not a primitive type!
Figure 10.27 StockAverage program illustrating ArrayList of Double objects















































   448   449   450   451   452