String as switch statement

Possible Duplicate:
Switch Statement with Strings in Java

I am trying to use switch statement on String but it gives compilation error. If any one suggest me how to use String in switch-case statement , it will be helpful to me.


There is a way if you really really want to use switch statements. Create an enum class which includes the switch statement cases

public enum MustUseSwitch{
    value1,
    value2,
    value3;
}

and then use the enum to switch to statements.

switch(MustUseSwitch.valueOf(stringVariable)){
    case value1:
        System.out.println("Value1!");
        break;
    case value2:
        System.out.println("Value2!");
        break;
    case value3:
        System.out.println("Value3!");
       break;
}

As already said, you can't. For technical details you can refer to the specification about compiling switches. With Java SE 7, this functionality has been implemented. See this page for an example using switch on String with JDK 7.

Maybe this question could be helpful too.


You can't. Use if/else if/else if/else. Unless you are on Java7. This answer on this duplicate question can explain it far better than I can: https://stackoverflow.com/a/338230/3333

链接地址: http://www.djcxy.com/p/84506.html

上一篇: 为什么Java中的switchcase语句是这样工作的?

下一篇: 字符串作为switch语句