简体   繁体   中英

Problem with using break statement in my program to calculate leap year using switch statement

public class MonthDayCal {
    public static boolean isLeapYear(int year) {
        if (year < 1 || year > 9999)
            return false;
        else {

            switch (year % 4) {
            case 0:
                if ((year % 100) == 0) {
                    if ((year % 400) == 0) {
                        return true;
                    } else
                        return false;
                } else
                    return true;
                break; // <--java : unreachable statement

            default:
                return false;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(isLeapYear(2100));
    }
}

Problem with using break statement in my program to calculate leap year using switch statement. Why i can't use break here? If i remove this break, the program runs correct. Shouldn't i use break to get out of case when year is divisible by 4 and stop the switch block.

The break statement is never reached, since all execution paths of case 0 always end in a return statement.

Therefore it's not needed.

If, instead of a return statement, you assigned a value to a variable, you would need the break statement:

boolean result = false;
if(year<1 || year>9999)
    result = false;
else {
    switch(year%4){
        case 0:
            if((year%100)==0){
                if((year%400)==0){
                    result = true;
                }
                else
                    result = false;
            }
            else
                result = true;
            break;

        default:
            result = false;
    }
}
return result;

Of course, you would be able to simplify the code in that case, so you wouldn't need the break statement after all:

boolean result = false;
if(year>=1 && year<=9999) {
    switch(year%4){
        case 0:
            if((year%100)==0){
                if((year%400)==0){
                    result = true;
                }
            } else {
                result = true;
            }
    }
}
return result;

That said, this doesn't look like a good scenario for using switch statement, since you only have two cases (or even one).

For example, you can write:

boolean result = false;
if(year>=1 && year<=9999 && year%4 == 0) {
    if((year%100)==0){
        if((year%400)==0){
            result = true;
        }
    } else {
        result = true;
    }
}
return result;

or even simpler (though it can still be further simplified):

boolean result = false;
if(year>=1 && year<=9999 && year%4 == 0) {
    if((year%100) != 0 || (year%400)==0) {
        result = true;
    }
}
return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM