Is there an analogous form of the following code:
if(month == 4,6,9,11)
{
do something;
}
Or must it be:
if(month == 4 ||
Perhaps if you are using C# you can do this:
public static class Extensions
{
public static bool IsIn(this Int32 intVal, params Int32[] vals)
{
return vals.Any(i => i == intVal)
}
}
int month = 4;
if (month.IsIn(4,6,9,11)) {
//do something
}
Don't do any specific checks. Try and convert to a valid date - if it throws an exception, report invalid date. After all you also need to check for day greater than 28 (or is it 29?) if the month is February.
This month
System.out.println("This month has " + new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH) + " days in it.");
if statement to check if there is 31 days on this month
if (31 == new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH))
{
System.out.println("31 days on this month");
}
else
{
System.out.println("Not 31 days in this month");
}
Write number of days for all months
Calendar cal = new GregorianCalendar();
for (int i = 0; i < 12; i++)
{
cal.set(2009, i, 1); //note that the month in Calendar goes from 0-11
int humanMonthNumber = i + 1;
int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("The " + humanMonthNumber + ". month has " + max + " days.");
}
output:
This month has 30 days in it.
Not 31 days in this month
The 1. month has 31 days.
The 2. month has 28 days.
The 3. month has 31 days.
The 4. month has 30 days.
The 5. month has 31 days.
The 6. month has 30 days.
The 7. month has 31 days.
The 8. month has 31 days.
The 9. month has 30 days.
The 10. month has 31 days.
The 11. month has 30 days.
The 12. month has 31 days.
Am I the only one to come up with
month_has_31days = month % 2 == month < 8
at least in C, can't check for java right now
For pretty much any you'll need to use the second option, but in most languages you can write something similar to
if [4,6,9,11].map{|day|==month}.inject(false){|all, elem| all|elem}
do thing
or better yet
if month in [4,6,9,11]:
do thing
You don't specify the language, but if you're using Java then yes, you have do do it the second way, or otherwise use switch:
switch(month) {
case 4:
case 6:
case 9:
case 11:
do something;
}
Alternatively, you might find it useful and cleaner (depending on the design) to not hard-code the values but keep them elsewhere:
private static final Collection<Integer> MONTHS_TO_RUN_REPORT = Arrays.asList(4, 6, 9, 11);
....
if (MONTHS_TO_RUN_REPORT.contains(month)) {
do something;
}