Java Reference
In-Depth Information
You're reading from a file, so you'll need a Scanner and a loop that reads scores
until there are no more scores to read:
Scanner input = new Scanner(new File("tally.dat"));
while (input.hasNextInt()) {
int next = input.nextInt();
// process next
}
To complete this code, you need to figure out how to process each value. You
know that next will be one of five different values: 0 , 1 , 2 , 3 , or 4 . If it is 0 , you want
to increment the counter for 0 , which is count[0] ; if it is 1 , you want to increment
the counter for 1 , which is count[1] , and so on. We have been solving problems like
this one with nested if/else statements:
if (next == 0) {
count[0]++;
} else if (next == 1) {
count[1]++;
} else if (next == 2) {
count[2]++;
} else if (next == 3) {
count[3]++;
} else { // next == 4
count[4]++;
}
But with an array, you can solve this problem much more directly:
count[next]++;
This line of code is so short compared to the nested if/else construct that you
might not realize at first that it does the same thing. Let's simulate exactly what hap-
pens as various values are read from the file.
When the array is constructed, all of the counters are initialized to 0 :
[0]
[1]
[2]
[3]
[4]
count
0
0
0
0
0
The first value in the input file is a 1 , so the program reads that into next . Then it
executes this line of code:
count[next]++;
Search WWH ::




Custom Search