Page 435 - Introduction to Programming with Java: A Problem Solving Approach
P. 435
passed to it by the driver’s constructor call. Note that it assigns the passed-in ft and c array references to the instance variables using the = operator. Previously, you learned to use a for loop, not the = operator, to make a copy of an array. Why is the = operator acceptable here? Because there’s no need to make a second copy of these arrays. After the constructor’s first assignment operation, the flightTimes instance vari- able array reference and the ft parameter array reference point to the same array object. And that’s appro- priate. Likewise, after the constructor’s second assignment operation, the cities instance variable array reference and the c parameter array reference point to the same array object.
Figure 10.19a’s promptForFlightTime method prompts the user for a departure city and a destina- tion city and prints the flight time for that flight. More specifically, it prints a legend of numbers and their associated city names (1 = Wichita, 2 = Topeka, and so on), it prompts the user to enter numbers for the departure and destination cities, and it prints the flight time between the specified cities. Note how user- entered city numbers start with 1 rather than 0 (1 = Wichita). That makes the program more user-friendly because people usually prefer to start counting at one rather than zero. Internally, the program stores city names in an array. Since all arrays start with a 0 index, the program has to translate between user-entered city numbers (which start at 1) and city array indexes (which start at 0). Note how that’s done with +1 and -1 in the promptForFlightTime method.
10.9 Two-DimensionalArrays 401
}
// end class FlightTimes
//*****************************************************************
// This method prints a table of all flight times.
Apago PDF Enhancer
public void displayFlightTimesTable()
{
}
// end displayFlightTimesTable
final String CITY_FMT_STR = "%5s"; ⎫⎬⎭ formatstrings final String TIME_FMT_STR = "%5d";
System.out.printf(CITY_FMT_STR, ""); // empty top-left corner
for (int col=0; col<cities.length; col++)
{
}
System.out.printf(CITY_FMT_STR, cities[col]);
System.out.println();
for (int row=0; row<flightTimes.length; row++)
System.out.printf(CITY_FMT_STR, cities[row]);
for (int col=0; col<flightTimes[0].length; col++)
{
}
// end for
{
}
System.out.printf(TIME_FMT_STR, flightTimes[row][col]);
System.out.println();
Figure 10.19b
FlightTimes class that displays intercity flight times—part B