Posted by: Chyne on: May 23, 2009
/* Exercise 7.12
* 1. Size of the array specified by the first command-line argument.
* 2. If no command-line argument is supplied, use 10 as the default size of the array.
*/
package Exercises;
public class SizeOfArray {
public static void main(String[] args) {
// check existence of command-line arguments
if (args.length == 0)
// set default size of array to 10
int array[] = new int[10]; // create array
System.out.printf(“%s%8s\n”, “Index”, “Value”); // column heading
// ouput each array element’s value
for (int counter = 0; counter < array.length; counter++) {
System.out.printf(“%5d%8s\n”, counter, array[counter]);
} // end for loop
} else {
// get array size from first command-line-argument
int arrayLength = Integer.parseInt(args[0]);
int array[] = new int[arrayLength]; // create array
// get initial value and increment from command-line argument
int initialValue = Integer.parseInt(args[1]);
int increment = Integer.parseInt(args[2]);
// calculate value for each array element
for (int counter = 0; counter < array.length; counter++) {
array[counter] = initialValue + increment * counter;
}
System.out.printf(“%s%8s\n”, “Index”, “Value”);
// display array index and value
for (int counter = 0; counter < array.length; counter++) {
System.out.printf(“%5d%8d\n”, counter, array[counter]);
} // end for loop
} // end if-else
} // end main
} // end class SizeOfArray