Java Reference
In-Depth Information
How do we refer to the fields of a
Part
object? As usual, it depends on whether the code is being written inside
the class
Part
or outside of it. If inside, the code can access the instance variables
name
and
price
directly, for
example,
part[2].name
. If outside, it must use the accessor and mutator methods to get and set the values in the
fields, for example,
part[2].getName()
.
If we have to deal with hundreds of parts, it would be better to store the parts' data in a file (
parts.dat
, say) and
read them into the array using a
for
or
while
loop. Suppose the data above was stored in the file like this (we write the
part name as one word so it can be read with
next
from the
Scanner
class):
AirFilter 8.75
BallJoint 29.95
Headlamp 36.99
Spark Plug 5.00
DiscPads 24.95
We can set up the
part
array with the following code:
Scanner in = new Scanner(new FileReader("parts.dat"));
Part[] part = new Part[5];
for (int h = 0; h < part.length; h++)
part[h] = new Part(in.next(), in.nextDouble());
This code is much better and more flexible. To read 1,000 parts, we just need to change the declaration of
part
and supply the data in the file. The code above remains unchanged. As usual, we don't
have
to fill the entire array with
parts data. We can read data until some end-of-data marker (
End
, say) is reached.
If we need to print the parts' data, we could use the following:
for (int h = 0; h < part.length; h++) part[h].printPart();
Suppose we want to interchange two parts in the array, for example,
part[2]
with
part[4]
. We do it the same
way we would interchange the values of any two variables of the same type, like this:
Part p = part[2];
part[2] = part[4];
part[4] = p;
It is useful to note that the actual objects remain where they were originally stored. All we do here is exchange the
addresses stored in
part[2]
and
part[4]
. In Figure
2-10
, think of the arrows as being interchanged.
2.11.1 Finding the Part with the Lowest Price
Suppose we want to find the part with the lowest price (in one sense, we want to find the “smallest” object). Assuming
we are writing this code outside the class
Part
, we can write
getLowestPrice
to return the position of the part with the
lowest price as follows:
public static int getLowestPrice(Part[] part, int lo, int hi) {
// return the position of the part with the lowest price
// from part[lo] to part[hi], inclusive
int small = lo;
for (int h = lo + 1; h <= hi; h++)
Search WWH ::
Custom Search