public class TotalNumbersErrors
1: // Fig. 18.14: TotalNumbersErrors.java
2: // Summing the elements of an ArrayList.
3: import java.util.ArrayList;
4:
5: public class TotalNumbersErrors
6: {
7: public static void main( String[] args )
8: {
9: // create, initialize and output ArrayList of Integers
10: // then display total of the elements
11: Integer[] integers = { 1, 2, 3, 4 };
12: ArrayList< Integer > integerList = new ArrayList< Integer >();
13:
14: for ( Integer element : integers )
15: integerList.add( element ); // place each number in integerList
16:
17: System.out.printf( "integerList contains: %s\n", integerList );
18: System.out.printf( "Total of the elements in integerList: %.1f\n",
19: sum( integerList ) );
20: } // end main
21:
22: // calculate total of ArrayList elements
23: public static double sum( ArrayList< Number > list )
24: {
25: double total = 0; // initialize total
26:
27: // calculate sum
28: for ( Number element : list )
29: total += element.doubleValue();
30:
31: return total;
32: } // end method sum
33: } // end class TotalNumbersErrors
34:
35: /**************************************************************************
36: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
37: * Pearson Education, Inc. All Rights Reserved. *
38: * *
39: * DISCLAIMER: The authors and publisher of this book have used their *
40: * best efforts in preparing the book. These efforts include the *
41: * development, research, and testing of the theories and programs *
42: * to determine their effectiveness. The authors and publisher make *
43: * no warranty of any kind, expressed or implied, with regard to these *
44: * programs or to the documentation contained in these books. The authors *
45: * and publisher shall not be liable in any event for incidental or *
46: * consequential damages in connection with, or arising out of, the *
47: * furnishing, performance, or use of these programs. *
48: *************************************************************************/