Is there an analogous form of the following code:
if(month == 4,6,9,11)
{
do something;
}
Or must it be:
if(month == 4 ||
If you're using C or Java, you can do this:
switch (month) {
case 4:
case 6:
case 9:
case 11:
do something;
break;
}
In some languages, you could even write case 4,6,9,11:
.
Other possibilities would be to create an array [4,6,9,11], some functional languages should allow something like if month in [4,6,9,11] do something;
As Lior said, it depends on the language.
EDIT: By the way, you could also do this (just for fun, bad code because not readable):
if ((abs(month-5) == 1) || (abs(month-10) == 1)) do_something;
For dates I use Joda Time mentioned earlier, but I understand if it's not applicable for you. If you just want it to look nice, you can first define a list with values that you're interested in and then check if your month is in that list:
// This should be a field in a class
// Make it immutable
public static final List<Integer> LONGEST_MONTHS =
Collections.immutableList(Arrays.asList(4,6,9,11));
// Somewhere in your code
if(LONGEST_MONTHS.contains(month)) {
doSomething();
}
Simpe Aux function (C#) that gives you the number of days of a given month:
private int GetDaysInMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1).Day;
}
Hope it helps
A complete solution, also taking leap year into account.
private static int getDaysInMonth(LocalDateTime localDateTime) {
int daysInMonth = 0;
int year = localDateTime.getYear();
int month = localDateTime.getMonth().getValue();
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
daysInMonth = 31;
break;
case 4: case 6:
case 9:case 11:
daysInMonth = 30;
break;
case 2:
if(((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0))) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default: System.out.println("Invalid month");
break;
}
return daysInMonth;
}
A rather literal translation into Java would be:
if (Arrays.binarySearch(new int[] { 4, 6, 9, 11 }, month) >= 0) {
I don't know what is so special about 4, 6, 9 and 11. You are probably better off using an enum, together with EnumSet
or perhaps a method on the enum. OTOH, perhaps JodaTime does something useful.
In Icon, you can do
if month = (4|6|9|11) then ...
You can also do
if a < b < c then ...