简体   繁体   English

如何使用Switch案例在Java中

[英]How to use Switch case In the Java

I am using Neatbeans 7.0 for Java programming. 我正在使用Neatbeans 7.0进行Java编程。 I have written a Switch case for selection of the program. 我写了一个Switch案例来选择程序。

switch(menu)
        {
            case 1:
            {
                //stmt
            }
            default:
            {
                //stmt
                return;
            }
        }

I am getting compile time error at switch(menu) 我在switch(menu)时遇到编译时错误switch(menu)

The Error is "strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)

(Alt-Enter shows hints)" Can any one please help me on this. (Alt-Enter显示提示)“任何人都可以帮助我。

String cases in switch statements are supported in Java SE 7 , but not in previous versions of Java. Java SE 7支持switch语句中的字符串大小写 ,但在以前的Java版本中不支持。 You need to compile with Java 7. 您需要使用Java 7进行编译。

Type of menu is String in your code. 菜单类型是代码中的String。 If you've JDK 1.6 then switch expression type should be int or char. 如果你有JDK 1.6,那么switch表达式类型应该是int或char。

You need to change project properties : 您需要更改项目属性

  1. Source : Source/Binary format : JDK7 来源:来源/二进制格式:JDK7
  2. Libraries : JDK1.7 图书馆:JDK1.7

I'm assuming here that menu is a string type, though it doesn't really match your case statements. 我在这里假设menu是一个字符串类型,虽然它与你的case语句不匹配。 Allowing the use of strings in switch statements was added in Java 7. 在Java 7中添加了允许在switch语句中使用字符串。

You can either switch to Java 7 and fix the case so that it checks against a string rather that the integral 1 , or convert menu to an integer and check that, such as with Integer.ParseInt() , something like: 您可以切换到Java 7并修复case以便它检查字符串而不是整数1 ,或将menu转换为整数并检查,例如使用Integer.ParseInt() ,类似于:

String menu = "1";
int menuint;
try {
    menuint = Integer.ParseInt (menu);
} catch (NumberFormatException e) {
    menuint = -1;
}
switch (menuint) {
   :

A switch works with the byte, short, char, and int primitive data types. 交换机使用byte,short,char和int原始数据类型。

String is unsupported until Java-6. 在Java-6之前不支持String。 Java 7 supports String object in switch-case. Java 7支持switch-case中的String对象。

In Java SE 7 and later, you can use a String object in the switch statement's expression. 在Java SE 7及更高版本中,您可以在switch语句的表达式中使用String对象。

Read more here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html 在这里阅读更多内容: http//docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

I think it should be: 我认为它应该是:

case "1":

.... ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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