【问题标题】:Problem with using break statement in my program to calculate leap year using switch statement在我的程序中使用 break 语句使用 switch 语句计算闰年的问题
【发布时间】:2020-06-17 19:19:30
【问题描述】:
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));
    }
}

在我的程序中使用 break 语句计算跳跃的问题 年份使用 switch 语句。为什么我不能在这里使用break? 如果我删除这个休息, 程序运行正确。当 year 可以被 4 整除并停止 switch 块时,我不应该使用 break 来摆脱情况吗?

【问题讨论】:

  • break; 之前的所有情况下,您都会返回。这意味着它无法访问...cases 只能有 returnbreak,因为它们都会导致离开范围。

标签: java switch-statement break


【解决方案1】:

永远不会到达break 语句,因为case 0 的所有执行路径总是以返回语句结束。

因此不需要。

如果您为变量赋值而不是返回语句,则需要break 语句:

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;

当然,在这种情况下你可以简化代码,所以你根本就不需要 break 语句:

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;

也就是说,这看起来不是使用switch 语句的好场景,因为您只有两种情况(甚至一种)。

例如,你可以写:

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;

甚至更简单(尽管还可以进一步简化):

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

【讨论】:

  • 我知道你做了什么,谢谢你的快速响应。那么这是否意味着如果我在每种情况下都返回一个值,我不应该使用 break 语句,因为它变得无法访问?
  • @R_Pal 这是正确的。编译器可以帮助您,但如果您将任何语句放在永远无法到达的地方,则不允许代码通过编译。
猜你喜欢
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2020-07-21
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2018-10-07
相关资源
最近更新 更多