首页 > 解决方案 > 将 if 语句转换为 swicth

问题描述

可以把这个程序变成一个 switch 语句吗?

if (Month * Day == Year){
    System.out.println("The date is magic");
} else {
    System.out.println("The date is not magic");
}

标签: javaif-statementswitch-statement

解决方案


要发表switch声明,您需要constant表达如下:

switch (month * day) {
    case 2000:
        System.out.println("The date is magic");
        break;
    default:
        System.out.println("The date is not magic");
}

但是你不能使用 a variable,你会constant expression required在编译时得到

switch (month * day) {
    case year:

  • switch用于多重比较,而不仅仅是一个
  • 请遵循 Java 命名约定 : attributes, variables, parameters,method必须以小写开头

推荐阅读