Java Reference
In-Depth Information
This application uses command-line arguments to specify the month and year to check.
The first argument is the month, which should be expressed as a number from 1 to 12.
The second argument is the year, which should be expressed as a full four-digit year.
After compiling the program, type the following at a command line to see the number of
days in April 2008:
java DayCounter 4 2008
The output is the following:
4/2008 has 30 days.
If you run it without arguments, the default month of January 2008 is used, and the out-
put is the following:
1/2008 has 31 days.
The
DayCounter
application uses a
switch
statement to count the days in a month. This
statement is part of the
countDays()
method in lines 13-40 of Listing 4.2.
The
countDays()
method has two
int
arguments:
month
and
year
. The number of days
is stored in the
count
variable, which is given an initial value of
-1
that is replaced by
the correct count later.
The
switch
statement that begins on line 15 uses
month
as its conditional value.
The number of days in a month is easy to determine for 11 months of the year. January,
March, May, July, August, October, and December have 31 days. April, June, September,
and November have 30 days.
The count for these 11 months is handled in lines 16-30 of Listing 4.2. Months are num-
bered from
1
(January) to
12
(December), as you would expect. When one of the
case
statements has the same value as
month
, every statement after that is executed until
break
or the end of the
switch
statement is reached.
February is a little more complex and is handled in lines 31-37 of the program. Every
leap year has 29 days in February, whereas other years have 28. A leap year must meet
either of the following conditions:
The year must be evenly divisible by 4 and not evenly divisible by 100.
n
The year must be evenly divisible by 400.
n
As you learned on Day 2, “The ABCs of Programming,” the modulus operator
%
returns
the remainder of a division operation. This is used with several
if
-
else
statements to
determine how many days there are in February, depending on what year it is.