I am writing a code that must meet a precondition, and if the conditions are all met then it will return true. I have tried multiple "if" statements but that doesn't seem to work. Nested if statements don't seem to be the answer here and I don't think "else if" statements would work. What I'm asking is, what is the correct way to do this? am I writing the if statements wrong?
heres my code:
public static boolean isLegitimate(int mon, int day, int year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
// TODO 1: Check if a date is valid.
//checks to see if the months are between 1 and 12
if((mon >= 1) && (mon <= 12)) {
}
//checks to see if the years are greater than 1
if (year > 0){
}
//checks to see if the days are between 1 and 31
if ((day >=0) && (day <=31)){
}
//This checks that if the month is February, is divisible by 4 evenly,
//and is divisible by 100 evenly, then the days can not exceed 29
if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){
if (day >29){
return false;
}
}
return true;
}
Just return false when a check fails. If one of the preconditions fail there is no need to check any further.
public static boolean isLegitimate(int mon, int day, int year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
// TODO 1: Check if a date is valid.
//checks to see if the months are between 1 and 12
if(mon<1) return false;
if(mon>12) return false;
//checks to see if the years are greater than 1
if(year<=0) return false;
//checks to see if the days are between 1 and 31
if(day<=0) return false;
if(day>31) return false;
//This checks that if the month is February, is divisible by 4 evenly,
//and is divisible by 100 evenly, then the days can not exceed 29
if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){
if (day >29){
return false;
}
}
return true;
}