Java Reference
In-Depth Information
18
19
// get initial value and increment from command-line arguments
20
int initialValue = Integer.parseInt(args[ 1 ]);
int increment = Integer.parseInt(args[ 2 ]);
21
22
23
// calculate value for each array element
for ( int counter = 0 ; counter < array.length; counter++)
array[counter] = initialValue + increment * counter;
24
25
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
}
33
}
34
} // end class InitArray
java InitArray
Error: Please re-enter the entire command, including
an array size, initial value and increment.
java InitArray 5 0 4
Index Value
0 0
1 4
2 8
3 12
4 16
java InitArray 8 1 2
Index Value
0 1
1 3
2 5
3 7
4 9
5 11
6 13
7 15
Fig. 7.21 | Initializing an array using command-line arguments. (Part 2 of 2.)
The output of the first execution shows that the application received an insufficient
number of command-line arguments. The second execution uses command-line argu-
ments 5, 0 and 4 to specify the size of the array (5), the value of the first element (0) and
the increment of each value in the array (4), respectively. The corresponding output shows
that these values create an array containing the integers 0, 4, 8, 12 and 16. The output
from the third execution shows that the command-line arguments 8, 1 and 2 produce an
array whose 8 elements are the nonnegative odd integers from 1 to 15.
Search WWH ::




Custom Search