Java Reference
In-Depth Information
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 8.5.
L
ISTING
8.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
double
[][][] data
8
=
new double
[NUMBER_OF_DAYS][NUMBER_OF_HOURS][
2
];
three-dimensional array
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;
18 data[day -
1
][hour -
1
][
1
] = humidity;
19 }
20
21
// Find the average daily temperature and humidity
22
for
(
int
i =
0
; i < NUMBER_OF_DAYS; i++) {
23
double
dailyTemperatureTotal =
0
, dailyHumidityTotal =
0
;
24
for
(
int
j =
0
; j < NUMBER_OF_HOURS; j++) {
25 dailyTemperatureTotal += data[i][j][
0
];
26 dailyHumidityTotal += data[i][j][
1
];
27 }
28
29
// Display result
30 System.out.println(
"Day "
+ i +
"'s average temperature is "
31 + dailyTemperatureTotal / NUMBER_OF_HOURS);
32 System.out.println(
"Day "
+ i +
"'s average humidity is "
33 + dailyHumidityTotal / NUMBER_OF_HOURS);
34 }
35 }
36 }
Day 0's average temperature is 77.7708
Day 0's average humidity is 0.929583
Day 1's average temperature is 77.3125
Day 1's average humidity is 0.929583
. . .
Day 9's average temperature is 79.3542
Day 9's average humidity is 0.9125
You can use the following command to run the program:
java Weather < Weather.txt
A three-dimensional array for storing temperature and humidity is created in line 8. The
loop in lines 12-19 reads the input to the array. You can enter the input from the keyboard, but
Search WWH ::
Custom Search