The next project gives you another look at each of the conditional tests you can use in your programs. For this project, you use Java’s built-in timekeeping feature, which keeps track of the current date and time, and present this information in sentence form.
Run NetBeans (or another program to create Java programs) and give a new class the name Clock
. This program is long, but most of it consists of long conditional statements. Type the full text of Listing 7.3 into the source code editor, and save the file.
1: import java.util.*;
2:
3: class Clock {
4: public static void main(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.
");
16: } else if (hour < 17) {
17: System.out.println("Good afternoon.
");
18: } else {
19: System.out.println("Good evening.
");
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: case 1:
39: System.out.print("January");
40: break;
41: case 2:
42: System.out.print("February");
43: break;
44: case 3:
45: System.out.print("March");
46: break;
47: case 4:
48: System.out.print("April");
49: break;
50: case 5:
51: System.out.print("May");
52: break;
53: case 6:
54: System.out.print("June");
55: break;
56: case 7:
57: System.out.print("July");
58: break;
59: case 8:
60: System.out.print("August");
61: break;
62: case 9:
63: System.out.print("September");
64: break;
65: case 10:
66: System.out.print("October");
67: break;
68: case 11:
69: System.out.print("November");
70: break;
71: case 12:
72: System.out.print("December");
73: }
74:
75: // display the date and year
76: System.out.println(" " + day + ", " + year + ".");
77: }
78: }
After the program compiles correctly, look it over to get a good idea about how the conditional tests are being used.
With the exception of Line 1 and Lines 6–11, the Clock
program contains material that has been covered up to this point. After a series of variables are set up to hold the current date and time, a series of if
or switch
conditionals are used to determine what information should be displayed.
This program contains several uses of System.out.println()
and System.out.print()
to display strings.
Lines 6–11 refer to a Calendar
variable called now
. The Calendar
variable type is capitalized because Calendar
is an object.
You learn how to create and work with objects during Hour 10, “Creating Your First Object.” For this hour, focus on what’s taking place in those lines rather than how it’s happening.
The Clock
program is made up of the following sections:
• Line 1 enables your program to use a class that is needed to track the current date and time: java.util.Calendar
.
• Lines 3–4 begin the Clock
program and its main()
statement block.
• Line 6 creates a Calendar
object called now
that contains the current date and time of your system. The now
object changes each time you run this program. (Unless the physical laws of the universe are altered and time stands still).
• Lines 7–11 create variables to hold the hour
, minute
, month
, day
, and year
. The values for these variables are pulled from the Calendar
object, which is the storehouse for all this information.
• Lines 14–20 display one of three possible greetings: “Good morning.”, “Good afternoon.”, or “Good evening.” The greeting to display is selected based on the value of the hour
variable.
• Lines 23–29 display the current minute along with some accompanying text. First, the text “It’s” is displayed in Line 23. If the value of minute
is equal to 0, Lines 25–28 are ignored because of the if
statement in Line 24. This statement is necessary because it would not make sense for the program to tell someone that it’s 0 minutes past an hour. Line 25 displays the current value of the minute
variable. A ternary operator is used in Lines 26–27 to display either the text “minutes” or “minute,” depending on whether minute
is equal to 1. Finally, in Line 28 the text past
is displayed.
• Lines 32–34 display the current hour by using another ternary operator. This ternary conditional statement in Line 33 causes the hour to be displayed differently if it is larger than 12, which prevents the computer from stating times like “15 o’clock.”
• Lines 37–73, almost half of the program, are a long switch
statement that displays a different name of the month based on the integer value stored in the month
variable.
• Line 76 finishes off the display by showing the current date and the year.
• Lines 77–78 close out the main()
statement block and then the entire Clock
program.
When you run this program, the output should display a sentence based on the current date and time. The output of the application is shown in the Output pane in Figure 7.3.
Run the program several times to see how it keeps up with the clock.
Now that you can use conditional statements, the overall intelligence of your Java programs has improved greatly. Your programs can evaluate information and use it to react differently in different situations, even if information changes as the program is running. They can decide between two or more alternatives based on specific conditions.
Programming a computer forces you to break a task down into a logical set of steps to undertake and decisions that must be made. Using the if
statement and other conditionals in programming also promotes a type of logical thinking that can reap benefits in other aspects of your life:
• “If he is elected president in November, I will seek a Cabinet position, else I will move to Canada.”
• “If my blind date is attractive, I’ll pay for dinner at an expensive restaurant, else we will go to Pizza Hut.”
• “If I violate my probation, the only team that will draft me is the Philadelphia Eagles.”
Q. The if
statement seems like the one that’s most useful. Is it possible to use only if
statements in programs and never use the others?
A. It’s possible to do without else
or switch
, and many programmers never use the ternary operator ?
. However, else
and switch
often are beneficial to use in your programs because they make the programs easier to understand. A set of if
statements chained together can become unwieldy.
Q. In the Clock
program, why is 1 added to Calendar.MONTH
to get the current month value?
A. This is necessary because of a quirk in the way that the Calendar class represents months. Instead of numbering them from 1 to 12 as you might expect, Calendar numbers months beginning with 0 in January and ending with 11 in December. Adding 1 causes months to be represented numerically in a more understandable manner.
Q. During this hour, opening and closing brackets {
and }
are not used with an if
statement if it is used in conjunction with only one statement. Isn’t it mandatory to use brackets?
A. No. Brackets can be used as part of any if
statement to surround the part of the program that’s dependent on the conditional test. Using brackets is a good practice to get into because it prevents a common error that might take place when you revise the program. If you add a second statement after an if
conditional and don’t add brackets, unexpected errors occur when the program is run.
Q. Does break
have to be used in each section of statements that follow a case
?
A. You don’t have to use break
. If you do not use it at the end of a group of statements, all the remaining statements inside the switch block statement are handled, regardless of the case value they are being tested with. However, in most cases you’re likely to want a break
statement at the end of each group.
Q. Why did the Thompson Twins get that name when they were a trio, they were not related, and none of them was named Thompson?
A. Band members Tom Bailey, Alannah Currie, and Joe Leeway called themselves the Thompson Twins in honor of Thomson and Thompson, a pair of bumbling detectives featured in the Belgian comic books The Adventures of Tintin.
The bowler-wearing detectives were physically indistinguishable except for a minor difference in the shape of their mustaches. Despite being terrible at their jobs, they were inexplicably assigned to important and sensitive missions. They often pursued Tintin for crimes that he did not commit.
As their names would indicate, the detectives were not related either.
The following questions see what condition you’re in after studying conditional statements in Java.
1. Conditional tests result in either a true
or false
value. Which variable type does this remind you of?
A. None. Stop pestering me with all these questions.
B. The long
variable type.
C. The boolean
type.
2. Which statement is used as a catch-all category in a switch
block statement?
A. default
B. otherwise
C. onTheOtherHand
3. What’s a conditional?
A. The thing that repairs messy split ends and tangles after you shampoo.
B. Something in a program that tests whether a condition is true or false.
C. The place where you confess your sins to a religious authority figure.
1. C. The boolean
variable type only can equal true
or false
, making it similar to conditional tests. If you answered A., I’m sorry, but there’s only 17 hours left and we’ve got a lot left to cover. Java doesn’t teach itself.
2. A. default
statements are handled if none of the other case
statements matches the switch
variable.
3. B. The other answers describe conditioner and a confessional.
To improve your conditioning in terms of Java conditionals, review the topics of this hour with the following activities:
• Add //
in front of a break
statement on one of the lines in the Clock
program to make it a comment, and then compile it and see what happens when you run it. Try it again with a few more break
statements removed.
• Create a short program that stores a value of your choosing from 1 to 100 in an integer variable called grade
. Use this grade
variable with a conditional statement to display a different message for all A, B, C, D, and F students. Try it first with an if
statement, and then try it with a switch
statement.
To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.
18.117.137.117