Java 中的变量值开关案例
我希望进行一个切换,其中 5 个案例在功能上相同,但还会有其他独特的案例。有没有办法列出处理 5 个不同值的 case 值?谢谢
I'm looking to make a switch where 5 of the cases are functionally identical, but then there will be other unique cases. Is there a way to list a case value that handles 5 different values? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以在开关中复合标签
将开关视为跳转到标签(可能与跳转(中断)到末尾相结合)会有所帮助。这意味着开关
将为“a”、“b”、“c”和“d”“做某事”和“做其他事”;而它只会为“e”和“f”“做其他事情”。最后,如果不是上述任何一个,它就会遇到“做某事”的默认块。
You can compound the labels in the switch
Thinking of a switch as a jump to a label (possibly coupled with a jump (the break) to the end) will help. That means the switch
will "do something" and "do something else" for 'a', 'b', 'c', and 'd'; while it will only "do something else" for 'e' and 'f'. Finally if it's not any of the above it hits the default block of "do something".
这很容易做到。不要只使用一个 case 值来处理所有 5 个不同的值,而是让 5 个 case 值相互传递,如下所示:
This is very easy to do. Instead of just having one case value that handles all 5 different values, let the 5 case values fall through to each other, like so:
只要您不在开关上放置
break;
,它就会跳到下一条语句。这样,你就可以得到这样的东西:
As long as you don't put a
break;
on a switch it will fall through to the next statement.In that way, you can have something like this:
是的,只需使用这样的开关:
Yes, just use a switch like this:
从 Java 12 开始,我相信它是受支持的。查看 JEP 354。我从未使用过该语法,但我认为对于您的情况,它会像这样运行。
相关说明 JEP 325 也很酷。
As of Java 12 I believe it is supported. Check out JEP 354. I have never used the syntax but I think it would run like this for your case.
on a related note JEP 325 is also cool.