Java Reference
In-Depth Information
figure 2.4
Simple demonstration
of arrays
1 import java.util.Random;
2
3 public class RandomNumbers
4 {
5 // Generate random numbers (from 1-100)
6 // Print number of occurrences of each number
7
8 public static final int DIFF_NUMBERS = 100;
9 public static final int TOTAL_NUMBERS = 1000000;
10
11 public static void main( String [ ] args )
12 {
13 // Create array; initialize to 0s
14 int [ ] numbers = new int [ DIFF_NUMBERS + 1 ];
15 for( int i = 0; i < numbers.length; i++ )
16 numbers[ i ] = 0;
17
18 Random r = new Random( );
19
20 // Generate the numbers
21 for( int i = 0; i < TOTAL_NUMBERS; i++ )
22 numbers[ r.nextInt( DIFF_NUMBERS ) + 1 ]++;
23
24 // Output the summary
25 for( int i = 1; i <= DIFF_NUMBERS; i++ )
26 System.out.println( i + ": " + numbers[ i ] );
27 }
28 }
Line 14 declares an array of integers that count the occurrences of each
number. Because arrays are indexed starting at zero, the +1 is crucial if we
want to access the item in position DIFF_NUMBERS . Without it we would have
an array whose indexible range was 0 to 99, and thus any access to index 100
would be out-of-bounds. The loop at lines 15 and 16 initializes the array
entries to zero; this is actually unnecessary, since by default, array elements
are initialized to zero for primitive and null for references.
The rest of the program is relatively straightforward. It uses the Random
object defined in the java.util library (hence the import directive at line 1).
The nextInt method repeatedly gives a (somewhat) random number in the
range that includes zero but stops at one less than the parameter to nextInt ;
thus by adding 1 , we get a number in the desired range. The results are output
at lines 25 and 26.
Since an array is a reference type, = does not copy arrays. Instead, if lhs
and rhs are arrays, the effect of
Always be sure to
declare the correct
array size. Off-by-
one errors are
common.
 
Search WWH ::




Custom Search