Java jdk 8 不允许在 switch 语句中使用字符串??为什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32655495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:56:00  来源:igfitidea点击:

jdk 8 does not allow string in switch statement ?? why

java

提问by Ali Rizvi

error:
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum constants are permitted code.  

Here is an example:

下面是一个例子:

String typeOfDay;
         switch (dayOfWeekArg) {
             case "Monday":
                 typeOfDay = "Start of work week";
                 break;
             case "Tuesday":
             case "Wednesday":
             case "Thursday":
                 typeOfDay = "Midweek";
                 break;
             case "Friday":
                 typeOfDay = "End of work week";
                 break;
             case "Saturday":
             case "Sunday":
                 typeOfDay = "Weekend";
                 break;
             default:
                 throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
         }

采纳答案by gla3dr

Cannot switch on a value of type String for source level below 1.7

You aren't using jdk 8. You either need to update java or fix the compiler compliance level of your IDE.

您没有使用 jdk 8。您需要更新 java 或修复 IDE 的编译器合规性级别。

To change compiler compliance level in Eclipse:

要在Eclipse 中更改编译器合规性级别:

Open Window > Preferences > Java > Compiler

打开窗口 > 首选项 > Java > 编译器

Change the Compiler compliance levelunder "JDK Compliance" to 1.8

将“JDK合规性”下的编译器合规级别更改为1.8



To change the source level in Netbeans:

要更改Netbeans 中的源级别:

Right-click the Libraries node in the Project view and choose Properties.

右键单击“项目”视图中的“库”节点并选择“属性”。

Choose "Sources" and set the Source Levelto 1.8

选择“Sources”并将Source Level设置为1.8



To change the project bytecode version in IntelliJ IDEA:

要在IntelliJ IDEA 中更改项目字节码版本:

Open File > Settings > Build, Execution, Deployment > Compiler > Java Compiler

打开文件 > 设置 > 构建、执行、部署 > 编译器 > Java 编译器

Set the Project bytecode versionto 1.8

项目字节码版本设置为 1.8

回答by KimKha

It's highly recommend you use if ("Monday".equals(dayOfWeekArg))instead of switch. Because it support all JDKs. And nowadays, most of applications are running on JDK 1.7.

强烈建议您使用if ("Monday".equals(dayOfWeekArg))而不是 switch。因为它支持所有的JDK。现在,大多数应用程序都在 JDK 1.7 上运行。