字符串作为switch语句 [英] String as switch statement

查看:882
本文介绍了字符串作为switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用Java中的字符串切换语句

我是尝试在String上使用switch语句,但它给出了编译错误。如果有人建议我如何在switch-case语句中使用String,它对我有帮助。

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.

推荐答案

有一个如果你真的想要使用switch语句的方式。
创建一个包含switch语句的枚举类

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;
}

这篇关于字符串作为switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆