Java Reference
In-Depth Information
results that will be added to it. We call the value
runningTimes.length
the
capacity
of the table —the total number of times the rat may be run through the
maze. The program must maintain, in some fashion, the number of times the rat
has been run so far, that is, the current size of the table. This is usually done using
an
int
variable. The usual convention is to declare the following:
//
Table of running times is
runningTimes[0..numberOfRuns - 1]
double
[] runningTimes;
int
numberOfRuns;
Here, we have declared not only the array but variable
numberOfRuns
,
which
says how many running times are in the table. Further, the comment says
where
these times are stored in the array —in the first
numberOfRuns
elements. Here is
an example array, which contains four running times.
0 1 2 3 numberOfRuns runningTimes.length
runni
29.5 99.9 99.0 47.2
?
We place a question mark in section
runningTimes[numberOfRuns..]
to indi-
cate that we do not know (or care) what values are in it.
Adding a new running time
t
(say) would then be done as follows —taking
the approach that the insertion is done only if there is room and that a message
is printed if there is no room:
if
(numberOfRuns < runningTimes.length) {
runningTimes[numberOfRuns]= t;
numberOfRuns= numberOfRuns + 1;
}
else
{
System.out.println("Sorry, array is full");
}
Sometimes we may want to delete the last value, perhaps because of a typ-
ing mistake. That is easy: simply decrement
runningTimes
:
runningTimes= runningTimes - 1;
Doing this when the table has four values, as shown above, terminates in this
state:
0 1 2 numberOfRuns runningTimes.length
r
29.5 99.9 99.0 47.2
?
Element
runningTimes[3]
still contains the value
47.2
. But we
do not care
about it; only elements
runningTimes[0..numberOfRuns-1]
are relevant.
In other situations, we may want to remove an arbitrary element
running-
Times[i]
, where
0 ≤ i < numberOfRuns
, as shown below:
Search WWH ::
Custom Search