Arrays

An array is a collection of variables of the same type.

The args[] array of a main() method is an array of Strings.

Consider a class which counts the occurrences of the digits 0-9. For example you might wish to test the randomness of a random number generator. If a random number generator is truly random, all digits should occur with equal frequency over a sufficiently long period of time.

You will do this by creating an array of ten ints called ndigit. The zeroth component of ndigit will track the number of zeros; the first component will track the numbers of ones and so forth. The RandomTest program below tests Java's random number generator to see if it produces apparently random numbers.

import java.util.Random;

class RandomTest {

  public static void main (String args[]) {
  
    int[] ndigits = new int[10];
    
    Random myRandom = new Random();
  
    // Initialize the array 
    for (int i = 0; i < 10; i++) {
      ndigits[i] = 0;
    }
    // Test the random number generator a whole lot
    for (long i=0; i < 100000; i++) {
      // generate a new random number between 0 and 9
      double x = myRandom.nextDouble() * 10.0;
      int n = (int) x;
      //count the digits in the random number
      ndigits[n]++;
    }
    
    // Print the results
    for (int i = 0; i < 10; i++) {
      System.out.println(i+": " + ndigits[i]);
    }
  }
  
}

Below is one possible output from this program. If you run it your results should be slightly different. After all this is supposed to be random. These results are pretty much what you would expect from a reasonably random generator. If you have a fast CPU and some time to spare, try bringing the number of tests up to a billion or so, and see if the counts for the different digits get any closer to each other.

$ javac RandomTest.java
$ java RandomTest
0: 10171
1: 9724
2: 9966
3: 10065
4: 9989
5: 10132
6: 10001
7: 10158
8: 9887
9: 9907

There are three for loops in this program, one to initialize the array, one to perform the desired calculation, and a final one to print out the results. This is quite common in code that uses arrays.


Previous | Next | Top | Cafe au Lait

Copyright 1997-2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified June 3, 2005