Java Reference
In-Depth Information
For our purposes, let's write a program that reads a file of integers and that shows
the distribution of the leading digit. We'll read the data from a file and will run it on
several sample inputs. First, though, let's consider the general problem of tallying.
Tallying Values
In programming we often find ourselves wanting to count the number of occurrences
of some set of values. For example, we might want to know how many people got a
100 on an exam, how many got a 99, how many got a 98, and so on. Or we might
want to know how many days the temperature in a city was above 100 degrees, how
many days it was in the 90's, how many days it was in the 80's, and so on. The
approach is very nearly the same for each of these tallying tasks. Let's look at a small
tallying task in which there are only five values to tally.
Suppose that a teacher scores quizzes on a scale of 0 to 4 and wants to know the
distribution of quiz scores. In other words, the teacher wants to know how many
scores of 0 there are, how many scores of 1, how many scores of 2, how many scores
of 3, and how many scores of 4. Suppose that the teacher has included all of the
scores in a data file like the following:
1410321420
3023043341
2413143324
2304144141
The teacher could hand-count the scores, but it would be much easier to use a
computer to do the counting. How can you solve the problem? First you have to
recognize that you are doing five separate counting tasks: You are counting the
occurrences of the number 0, the number 1, the number 2, the number 3, and the
number 4. You will need five counters to solve this problem, which means that an
array is a great way to store the data. In general, whenever you find yourself think-
ing that you need n of some kind of data, you should think about using an array of
length n.
Each counter will be an int , so you want an array of five int values:
int[] count = new int[5];
This line of code will allocate the array of five integers and will auto-initialize
each to 0 :
[0]
[1]
[2]
[3]
[4]
count
0
0
0
0
0
 
 
Search WWH ::




Custom Search