Java Reference
In-Depth Information
x.length
is
2
,
x[0].length
and
x[1].length
are
2
, and
X[0][0].length
,
x[0][1].length
,
x[1][0].length
, and
x[1][1].length
are
5
.
7.8.1 Case Study: Daily Temperature and Humidity
Suppose a meteorology station records the temperature and humidity every hour of every day and
stores the data for the past ten days in a text file named
Weather. txt
(see
www.cs.armstrong.edu/liang/data/Weather.txt
).
Each line of the file consists of four numbers that indi-
cate the day, hour, temperature, and humidity. The contents of the file may look like the one in (a).
Day
Temperature
Day
Temperature
Hour
Humidity
Hour
Humidity
1
1
76.4
0.92
10
24
98.7
0.74
1
2
77.7
0.93
1
2
77.7
0.93
. . .
10
. . .
10
23
97.7
0.71
23
97.7
0.71
10
24
98.7
0.74
1
1
76.4
0.92
(a)
(b)
Note that the lines in the file are not necessarily in increasing order of day and hour. For
example, the file may appear as shown in (b).
Your task is to write a program that calculates the average daily temperature and humidity
for the
10
days. You can use the input redirection to read the file and store the data in a three-
dimensional array named
data
. The first index of
data
ranges from
0
to
9
and represents
10
days, the second index ranges from
0
to
23
and represents
24
hours, and the third index ranges
from
0
to
1
and represents temperature and humidity, as depicted in the following figure:
Which day
Which hour
Temperature or humidity
data [ i ] [ j ] [ k ]
Note that the days are numbered from
1
to
10
and the hours from
1
to
24
in the file.
Because the array index starts from
0
,
data[0][0][0]
stores the temperature in day
1
at
hour
1
and
data[9][23][1]
stores the humidity in day
10
at hour
24
.
The program is given in Listing 7.5.
L
ISTING
7.5
Weather.java
1
import
java.util.Scanner;
2
3
public class
Weather {
4
public static void
main(String[] args) {
5
final int
NUMBER_OF_DAYS =
10
;
6
final int
NUMBER_OF_HOURS =
24
;
7
8
9
10 Scanner input =
new
Scanner(System.in);
11
// Read input using input redirection from a file
12
for
(
int
k =
0
; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++) {
13
int
day = input.nextInt();
14
int
hour = input.nextInt();
15
double
temperature = input.nextDouble();
16
double
humidity = input.nextDouble();
17 data[day -
1
][hour -
1
][
0
] = temperature;
double
[][][] data
three-dimensional array
=
new double
[NUMBER_OF_DAYS][NUMBER_OF_HOURS][
2
];