View Full Version : What does this snippet do?
adamweyant
05-21-2007, 06:27 AM
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.
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;
}
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.
That is it really...
Ess
adamweyant
05-21-2007, 01:49 PM
Wow, thank you so much. Great explanation.
ghell
05-23-2007, 01:54 AM
If you remove the comments this should be much more understandable. I have no idea how case 8 (september) has anything to do with "\b" for example.
By the way, usually switch-case will have a "break" at the end of each case to stop control falling down into the next case statement. This has been omitted here to make more than 1 statement flow into each other and then return out at 30, 31 or the leap year calculation.
javabits
05-23-2007, 07:22 PM
You can also rewrite it to look like this:
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 ];
}
semper fi...
ghell
05-23-2007, 08:35 PM
Or
private static final short[] daysInMonths =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public static short daysInMonth(short monthIn, short yearIn)
{
if(monthIn == 1 && isLeapYear(yearIn))
return 29;
else
return daysInMonths[monthIn];
}The "else" line isn't needed but some people like it.
This is probably the most efficient implementation unless you use byte instead of short (not that it probably matters on something so small), and maybe the simplest.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.