Counting Digits
We’ve already seen one example of an array. Main methods in an application store the command line arguments in an array of strings called args
.
As our second example let’s consider a class that counts the occurrences of the digits 0-9 in decimal expansion of the number pi, for example. This is an issue of some interest both to pure number theorists and to theologians. See, for example, Carl Sagan’s Contact and John Updike’s Roger’s Version. More realistically we 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.
We will do this by creating an array of ten longs called ndigit
. The zeroth element of ndigit
will track the number of zeroes in the input stream; the first element of ndigit
will track the numbers of 1’s and so on. We’ll test Java’s random number generator and see if it produces apparently random numbers.
import java.util.*;
class RandomTest {
public static void main (String args[]) {
int[] ndigits = new int[10];
double x;
int n;
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
x = myRandom.nextDouble() * 10.0;
n = (int) x;
//count the digits in the random number
ndigits[n]++;
}
// Print the results
for (int i = 0; i <= 9; i++) {
System.out.println(i+": " + ndigits[i]);
}
}
}
We’ve got three for
loops in this code, 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.