Java Reference
In-Depth Information
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
doing so will be awkward. For convenience, we store the data in a file and use input redirection
to read the data from the file. The loop in lines 24-27 adds all temperatures for each hour in a
day to
dailyTemperatureTotal
and all humidity for each hour to
dailyHumidityTotal
.
The average daily temperature and humidity are displayed in lines 30-33.
7.8.2 Case Study: Guessing Birthdays
Listing 3.3, GuessBirthday.java, gives a program that guesses a birthday. The program can be
simplified by storing the numbers in five sets in a three-dimensional array, and it prompts the
user for the answers using a loop, as shown in Listing 7.6. The sample run of the program can
be the same as shown in Listing 3.3.
L
ISTING
7.6
GuessBirthdayUsingArray.java
1
import
java.util.Scanner;
2
3
public class
GuessBirthdayUsingArray {
4
public static void
main(String[] args) {
5
int
day =
0
;
// Day to be determined
6
int
answer;
7
8
9 {{
1
,
3
,
5
,
7
},
10 {
9
,
11
,
13
,
15
},
int
[][][] dates = {
three-dimensional array