Source of TotalNumbers.java


  1: // Fig. 18.14: TotalNumbers.java
  2: // Summing the elements of an ArrayList.
  3: import java.util.ArrayList;
  4: 
  5: public class TotalNumbers
  6: {
  7:    public static void main( String args[] ) 
  8:    {
  9:       // create, initialize and output ArrayList of Numbers containing 
 10:       // both Integers and Doubles, then display total of the elements 
 11:       Number[] numbers = { 1, 2.4, 3, 4.1 }; // Integers and Doubles
 12:       ArrayList< Number > numberList = new ArrayList< Number >();
 13: 
 14:       for ( Number element : numbers ) 
 15:          numberList.add( element ); // place each number in numberList
 16: 
 17:       System.out.printf( "numberList contains: %s\n", numberList );
 18:       System.out.printf( "Total of the elements in numberList: %.1f\n", 
 19:          sum( numberList ) );
 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 TotalNumbers
 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:  *************************************************************************/