Source of VarargsTest.java


  1: // Fig. 7.20: VarargsTest.java
  2: // Using variable-length argument lists.
  3: 
  4: public class VarargsTest 
  5: {
  6:    // calculate average
  7:    public static double average( double... numbers )
  8:    {
  9:       double total = 0.0; // initialize total
 10: 
 11:       // calculate total using the enhanced for statement
 12:       for ( double d : numbers )
 13:          total += d;
 14: 
 15:       return total / numbers.length;
 16:    } // end method average
 17: 
 18:    public static void main( String args[] ) 
 19:    {
 20:       double d1 = 10.0;
 21:       double d2 = 20.0;
 22:       double d3 = 30.0;
 23:       double d4 = 40.0;
 24: 
 25:       System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n",
 26:          d1, d2, d3, d4 );
 27: 
 28:       System.out.printf( "Average of d1 and d2 is %.1f\n", 
 29:          average( d1, d2 ) ); 
 30:       System.out.printf( "Average of d1, d2 and d3 is %.1f\n", 
 31:          average( d1, d2, d3 ) );
 32:       System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", 
 33:          average( d1, d2, d3, d4 ) );
 34:    } // end main
 35: } // end class VarargsTest
 36: 
 37: 
 38: /**************************************************************************
 39:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 40:  * Pearson Education, Inc. All Rights Reserved.                           *
 41:  *                                                                        *
 42:  * DISCLAIMER: The authors and publisher of this book have used their     *
 43:  * best efforts in preparing the book. These efforts include the          *
 44:  * development, research, and testing of the theories and programs        *
 45:  * to determine their effectiveness. The authors and publisher make       *
 46:  * no warranty of any kind, expressed or implied, with regard to these    *
 47:  * programs or to the documentation contained in these books. The authors *
 48:  * and publisher shall not be liable in any event for incidental or       *
 49:  * consequential damages in connection with, or arising out of, the       *
 50:  * furnishing, performance, or use of these programs.                     *
 51:  *************************************************************************/