1. Member
Join Date
Jun 2007
Posts
91
Rep Power
0

## Help with switches

Can someone please explain to me how this section of code works.
It is used in a date program.
It accepts a month and a year then finds the number of days in the month.
I just don't have much experience with switches.

Java Code:
```public static short daysInMonth(short monthIn, short yearIn) {
switch(monthIn) {
case 3: // '\003'
case 5: // '\005'
case 8: // '\b'
case 10: // '\n'
return 30;

case 1: // '\001'
return (short)(isLeapYear(yearIn) ? 29 : 28);

case 0: // '\0'
case 2: // '\002'
case 4: // '\004'
case 6: // '\006'
case 7: // '\007'
case 9: // '\t'
case 11: // '\013'
return 31;
}
return 0;

}```
Thanks
Daniel:o

2. Senior Member
Join Date
Jun 2007
Posts
114
Rep Power
0
You can consider switch statements as a chain of if..else statements.

In the code you supplied above, the switch statement returns the total number of days in a month...provided an integer value is supplied representing a given month in a given year.

What you should note here is that the months count starts from 0 to 11. So, January is represented by number zero...February is represented by number 1...and so on..

As you know...all months (except February) either have 30 or 31 days. So...for the months that has 30 days...the months have been grouped...so is the case for the months that have 31 days.

The only case is for February which is represented by the integer value of 1. Here...the leap year is checked...to verify if it is 28 or 29 days for a given year.

Greetings
Albert:rolleyes:

3. Member
Join Date
Jun 2007
Posts
92
Rep Power
0
You can also rewrite it to look like this:

Java Code:
```public static short daysInMonth(short monthIn, short yearIn)
{
short [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += isLeapYear(yearIn) ? 1 : 0;
return daysInMonths[ monthIn ];
}```
Greetings
Marcus:cool:

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•