Java Reference
In-Depth Information
doing so will be awkward. For convenience, we store the data in a file and use input redirec-
tion 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 dailyHumidity-
Total . The average daily temperature and humidity are displayed in lines 30-33.
8.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 8.6. The sample run of the program can
be the same as shown in Listing 4.3.
L ISTING 8.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 int [][][] dates = {
9 {{ 1 , 3 , 5 , 7 },
10 { 9 , 11 , 13 , 15 },
11 { 17 , 19 , 21 , 23 },
12 { 25 , 27 , 29 , 31 }},
13 {{ 2 , 3 , 6 , 7 },
14 { 10 , 11 , 14 , 15 },
15 { 18 , 19 , 22 , 23 },
16 { 26 , 27 , 30 , 31 }},
17 {{ 4 , 5 , 6 , 7 },
18 { 12 , 13 , 14 , 15 },
19 { 20 , 21 , 22 , 23 },
20 { 28 , 29 , 30 , 31 }},
21 {{ 8 , 9 , 10 , 11 },
22 { 12 , 13 , 14 , 15 },
23 { 24 , 25 , 26 , 27 },
24 { 28 , 29 , 30 , 31 }},
25 {{ 16 , 17 , 18 , 19 },
26 { 20 , 21 , 22 , 23 },
27 { 24 , 25 , 26 , 27 },
28 { 28 , 29 , 30 , 31 }}};
29
30 // Create a Scanner
31 Scanner input = new Scanner(System.in);
32
33 for ( int i = 0 ; i < 5 ; i++) {
34 System.out.println( "Is your birthday in Set" + (i + 1 ) + "?" );
35 for ( int j = 0 ; j < 4 ; j++) {
36 for ( int k = 0 ; k < 4 ; k++)
37 System.out.printf( "%4d" , dates[i][j][k]);
38 System.out.println();
39 }
40
41 System.out.print( "\nEnter 0 for No and 1 for Yes: " );
42 answer = input.nextInt();
43
44 if (answer == 1 )
45 day += dates[i][ 0 ][ 0 ];
three-dimensional array
Set i
add to day
 
 
Search WWH ::




Custom Search