Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

88 HOUR 7:Using Conditional Tests to Make Decisions


LISTING 7.3 TheClockProgram
1: importjava.util.*;
2:
3: classClock {
4: public static voidmain(String[] arguments) {
5: // get current time and date
6: Calendar now = Calendar.getInstance();
7: int hour = now.get(Calendar.HOUR_OF_DAY);
8: int minute = now.get(Calendar.MINUTE);
9: int month = now.get(Calendar.MONTH) + 1;
10: int day = now.get(Calendar.DAY_OF_MONTH);
11: int year = now.get(Calendar.YEAR);
12:
13: // display greeting
14: if (hour < 12) {
15: System.out.println(“Good morning.\n”);
16: } else if(hour < 17) {
17: System.out.println(“Good afternoon.\n”);
18: } else{
19: System.out.println(“Good evening.\n”);
20: }
21:
22: // begin time message by showing the minutes
23: System.out.print(“It’s”);
24: if (minute != 0) {
25: System.out.print(“ “ + minute + “ “);
26: System.out.print( (minute != 1)? “minutes”:
27: “minute”);
28: System.out.print(“ past”);
29: }
30:
31: // display the hour
32: System.out.print(“ “);
33: System.out.print( (hour > 12)? (hour - 12) : hour );
34: System.out.print(“ o’clock on “);
35:
36: // display the name of the month
37: switch(month) {
38: case1:
39: System.out.print(“January”);
40: break;
41: case2:
42: System.out.print(“February”);
43: break;
44: case3:
45: System.out.print(“March”);
46: break;
47: case4:
48: System.out.print(“April”);
49: break;
50: case5:
51: System.out.print(“May”);
Free download pdf