HTML and CSS Reference
In-Depth Information
Perhaps you've already noticed a problem with the dayCount array: February has 29
days, not 28, during a leap year. For the daysInMonth() function to return the correct value
for the month of February, it must examine the year value and then set the value for the
number of days in February to either 28 or 29 based on whether the current year is a leap
year. You can do this through a conditional statement. A conditional statement is a state-
ment that runs a command or command block only when certain circumstances are met.
Exploring the if Statement
The most common conditional statement is the if statement, which has the structure
if ( condition ) {
commands
}
where condition is a Boolean expression that is either true or false , and commands
is the command block that is run if condition is true. If only one command is run, you
can eliminate the command block and enter the if statement as follows:
if ( condition ) command ;
The condition expression uses the same comparison and logical operators you used
with conditional operators in the previous tutorial. However, unlike a conditional opera-
tor, which is limited to changing the value of a variable based on a condition, a condi-
tional statement is used to run a particular command or command block. For example,
the following if statement would set the value of the dayCount array for February to 29
if the year value were 2016 (a leap year):
if (thisYear == 2016) {
dayCount[1] = 29;
}
For the calendar app, you'll need to create a conditional expression that tests whether
the current year is a leap year and then sets the value of dayCount [1] appropriately. The
general rule is that leap years are divisible by 4, so you'll start by looking at operators
that can determine whether the year is divisible by 4. One way is to use the % operator,
which is also known as the modulus operator. The modulus operator returns the integer
remainder after dividing one integer by another. For example, the expression
15 % 4
returns the value 3 because 3 is the remainder after dividing 15 by 4. To test whether a
year value is divisible by 4, you'll use the conditional expression
thisYear % 4 == 0
where the thisYear variable contains the four-digit year value. The following is the com-
plete if statement to change the value of the dayCount array for the month of February:
if (thisYear % 4 == 0) {
dayCount[1] = 29;
}
You'll add this if statement to the daysInMonth() function now.
Search WWH ::

Custom Search