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

(singke) #1
ptg7068951

90 HOUR 7:Using Conditional Tests to Make Decisions


The Clockprogram 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 Clockprogram and its main()statement block.
. Line 6 creates a Calendarobject called nowthat contains the current
date and time of your system. The nowobject 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 morn-
ing.”, “Good afternoon.”, or “Good evening.” The greeting to display
is selected based on the value of the hourvariable.
. Lines 23–29 display the current minute along with some accompany-
ing text. First, the text “It’s” is displayed in Line 23. If the value of
minuteis equal to 0, Lines 25–28 are ignored because of the ifstate-
ment 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 minutevariable. A
ternary operator is used in Lines 26–27 to display either the text
“minutes” or “minute,” depending on whether minuteis equal to 1.
Finally, in Line 28 the text pastis displayed.
. Lines 32–34 display the current hour by using another ternary opera-
tor. 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 switchstatement
that displays a different name of the month based on the integer
value stored in the monthvariable.
. 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
Clockprogram.


When you run this program, theoutput 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.
Free download pdf