The code that is shown below is working fine but only for one part, the if...else statement which must return -1 if the inputted month is less than 1 or more than 12 and the inputted year less than 1 or more than 9999
I have compile it many times, I have even tried rearranging the conditions like changing the less than to more than then putting the entire switch statement into the if statement. nothing seems to be working
public static int getDaysInMonth(int month, int year) {
int maxDay = 31;
int secMaxDay = 30;
int specialDay = 29;
int minDay = 28;
if ((month < 1 || month > 12) && (year < 1 || year > 9999)) {
return -1;
} else {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return maxDay;
case 2:
if (isLeapYear(year)){
return specialDay;
} else {
return minDay;
}
default:
return secMaxDay;
}
}
}
The expected output for my above code is, when either the month or year or both have a value of less than 1 or more than the max value, it should return -1.
At the moment you are returning "-1" only if both conditions are true.
'&&
' will only return true
if both contitions are true
.
So you should change
if ((month < 1 || month > 12) && (year < 1 || year > 9999))
with
if ((month < 1 || month > 12) || (year < 1 || year > 9999))
You can simplify it like:
if (month < 1 || month > 12 || year < 1 || year > 9999)
The problem was that (for instance) if month < 1 || month > 12
is true but year < 1 || year > 9999
is false, then true && false
returns false
.