Java Reference
In-Depth Information
With the addition of a header for the output, the complete program is as follows:
1 // Reads a series of values and reports the frequency of
2 // occurrence of each value.
3
4 import java.io.*;
5 import java.util.*;
6
7 public class Tally {
8 public static void main(String[] args)
9 throws FileNotFoundException {
10 Scanner input = new Scanner( new File("tally.dat"));
11 int [] count = new int [5];
12 while (input.hasNextInt()) {
13 int next = input.nextInt();
14 count[next]++;
15 }
16 System.out.println("Value\tOccurrences");
17 for ( int i = 0; i < count.length; i++) {
18 System.out.println(i + "\t" + count[i]);
19 }
20 }
21 }
Given the sample input file shown earlier, this program produces the following output:
Value Occurrences
0 5
1 9
2 6
3 9
4 11
It is important to realize that a program written with an array is much more flexible
than programs written with simple variables and if/else statements. For example,
suppose you wanted to adapt this program to process an input file with exam scores that
range from 0 to 100. The only change you would have to make would be to allocate a
larger array:
int[] count = new int[101];
If you had written the program with an if/else approach, you would have to add 96
new branches to account for the new range of values. When you use an array solution,
you just have to modify the overall size of the array. Notice that the array size is one
Search WWH ::




Custom Search