Java Reference
In-Depth Information
more than the highest score (101 rather than 100) because the array is zero-based and
because you can actually get 101 different scores on the test, including 0 as a possibility.
Completing the Program
Now that we've explored the basic approach to tallying, we can fairly easily adapt it
to the problem of analyzing a data file to find the distribution of leading digits. As we
stated earlier, we're assuming that we have a file of integers. To count the leading
digits, we will need to be able to get the leading digit of each. This task is specialized
enough that it deserves to be in its own method.
So let's first write a method called firstDigit that returns the first digit of an
integer. If the number is a one-digit number, then the number itself will be the
answer. If the number is not a one-digit number, then we can chop off its last digit
because we don't need it. If we do the chopping in a loop, then eventually we'll get
down to a one-digit number (the first digit). This leads us to write the following loop:
while (result >= 10) {
result = result / 10;
}
We don't expect to get any negative numbers, but it's not a bad idea to make sure
we don't have any negatives. So putting this into a method that also handles nega-
tives, we get the following code:
public static int firstDigit(int n) {
int result = Math.abs(n);
while (result >= 10) {
result = result / 10;
}
return result;
}
In the previous section we explored the general approach to tallying. In this case
we want to tally the digits 0 through 9, so we want an array of length 10. Otherwise
the solution is nearly identical to what we did in the last section. We can put the tally-
ing code into a method that constructs an array and returns the tally:
public static int[] countDigits(Scanner input) {
int[] count = new int[10];
while (input.hasNextInt()) {
int n = input.nextInt();
count[firstDigit(n)]++;
}
return count;
}
 
Search WWH ::




Custom Search