在开关情况下,是否可以将整数和字符串用作案例?
我已经环顾四周,但没有真正找到有关此的直接信息,所以我想直接询问它。
是否可以在开关情况下使用整数和字符串?我知道开关是一种类型(int,string等),但是有办法解决吗?例如:
int list;
switch(list)
{
case 1: ...code...
break;
case 2: ...code...
break;
case XY: ...code...
break;
}
我知道这会引发不匹配数据的错误。但是是否可以解决错误?诸如Integer.toString()之类的东西是否可以将INT转换为字符串?只想获得有关该主题的一些想法和信息。
I've done some looking around and haven't really found much direct info on this so I'd like to just ask it directly.
Is it possible to use integers and strings in a switch case? I know the switch is of one type (int, string, etc), but is there a way around it? For example:
int list;
switch(list)
{
case 1: ...code...
break;
case 2: ...code...
break;
case XY: ...code...
break;
}
I know this would throw an error of mismatched data. But is it possible to work around the error? Would something like Integer.toString() work to convert the int to a string? Just want to get some thoughts and information on the subject.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您要寻找的称为Switch语句的模式匹配。这是Java 17提供的功能,您可以看到在这里。但是,此功能仍在预览中。考虑到这一点,您可以修改代码看起来像这样,然后启用预览功能以使其正常工作。一个示例是:
然后在编译时启用预览功能。
What you are looking for is called pattern matching for switch statements. This is a feature that has been offered with Java 17 as you can see here. However, this feature is still in preview. With that in mind you could modify your code to look like so, and then enable preview features in order to make it work. An example would be:
And then enabled preview features when compiling.
一种方法,即使在Java的较旧版本上也可以使用,并且不需要使用最新版本的预览功能是结合使用
instanceof
和switch> switch
:输出:
1
2
xy
不是1或2
xy
A way to do this that should work even on older versions of Java and doesn't require the use of preview features from the latest versions is to combine the use of
instanceof
andswitch
:Output:
1
2
XY
Not 1 or 2
NOT XY
好吧,这种方法是不可能的,必须是相同的数据类型
但是您可以
尝试将INT转换为字符串,然后您可以。
Well this approach is not possible, it has to be same data type
But you can to this
Try to convert the int to string then you will be fine.
您可以使用枚举。
注意以下代码示例:
You can use enum.
Pay attention to the following code example:
我认为,它会起作用。
这取决于您的JDK,因为Switch语句已被“调谐”几次。如果您可以在开关语句中“比较”字符串,那么这将起作用,并且阶段是您的。
我查一下,您至少需要JDK7。 https://docs.oracle.com/javase/8/docs/technotes/guides/guides/langueage/lange/strings-switch.html
将INTS转换为类似的字符串:
对不起,对许多编辑,我只是为许多编辑讨厌我的智能手机。
I think, it will work.
It depends on your jdk, because the switch statement has been "tuned" a few times. If you can "compare" a String in a switch statement, then this will work and the stage is yours.
I looked it up, you need at least jdk7. https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html
Convert the ints to String like this:
Sorry for the many edits, I just hate my smartphone.