Source of InitArray.java


  1: // Fig. 7.21: InitArray.java
  2: // Using command-line arguments to initialize an array.
  3: 
  4: public class InitArray 
  5: {
  6:    public static void main( String args[] )
  7:    {
  8:       // check number of command-line arguments
  9:       if ( args.length != 3 )
 10:          System.out.println( 
 11:             "Error: Please re-enter the entire command, including\n" + 
 12:             "an array size, initial value and increment." );
 13:       else
 14:       {
 15:          // get array size from first command-line argument
 16:          int arrayLength = Integer.parseInt( args[ 0 ] ); 
 17:          int array[] = new int[ arrayLength ]; // create array
 18: 
 19:          // get initial value and increment from command-line argument
 20:          int initialValue = Integer.parseInt( args[ 1 ] );
 21:          int increment = Integer.parseInt( args[ 2 ] );
 22: 
 23:          // calculate value for each array element
 24:          for ( int counter = 0; counter < array.length; counter++ )
 25:             array[ counter ] = initialValue + increment * counter;
 26: 
 27:          System.out.printf( "%s%8s\n", "Index", "Value" );
 28:          
 29:          // display array index and value
 30:          for ( int counter = 0; counter < array.length; counter++ )
 31:             System.out.printf( "%5d%8d\n", counter, array[ counter ] );
 32:       } // end else
 33:    } // end main
 34: } // end class InitArray
 35: 
 36: 
 37: /**************************************************************************
 38:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 39:  * Pearson Education, Inc. All Rights Reserved.                           *
 40:  *                                                                        *
 41:  * DISCLAIMER: The authors and publisher of this book have used their     *
 42:  * best efforts in preparing the book. These efforts include the          *
 43:  * development, research, and testing of the theories and programs        *
 44:  * to determine their effectiveness. The authors and publisher make       *
 45:  * no warranty of any kind, expressed or implied, with regard to these    *
 46:  * programs or to the documentation contained in these books. The authors *
 47:  * and publisher shall not be liable in any event for incidental or       *
 48:  * consequential damages in connection with, or arising out of, the       *
 49:  * furnishing, performance, or use of these programs.                     *
 50:  *************************************************************************/