# Help with switches

• 07-04-2007, 09:34 AM
Daniel
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.

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
• 07-04-2007, 09:35 AM
Albert
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:
• 07-04-2007, 09:37 AM
Marcus
You can also rewrite it to look like this:

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: