java case 多个_Java – switch case,多个case调用相同的函数

由于我有多个String情况应该以相同的方式处理,我试过:

switch(str) {

// compiler error

case "apple", "orange", "pieapple":

handleFruit();

break;

}

但是我收到编译器错误.

在Java中,我是否应该逐个调用相同的函数:

switch(str) {

case "apple":

handleFruit();

break;

// repeat above thing for each fruit

...

}

没有简单的风格吗?

解决方法:

您必须为每个String使用case关键字,如下所示:

switch (str) {

//which mean if String equals to

case "apple": // apple

case "orange": // or orange

case "pieapple": // or pieapple

handleFruit();

break;

}

编辑02/05/2019

Java 12

从Java 12开始,提出了一种新的switch case语法,所以要解决这个问题,方法如下:

switch (str) {

case "apple", "orange", "pieapple" -> handleFruit();

}

现在,您可以用逗号分隔选项,箭头 – >然后你想要做的动作.

另一种语法也是:

考虑到每个case返回一个值,并且你想在变量中设置值,让我们假设handleFruit()返回一个String,旧的语法应该是:

String result; //

switch (str) {

//which mean if String equals to

case "apple": // apple

case "orange": // or orange

case "pieapple": // or pieapple

result = handleFruit(); //

break;

}

现在使用Java 12,你可以这样做:

String result = switch (str) { //

case "apple", "orange", "pieapple" -> handleFruit();

}

语法很好

标签:java,switch-statement

来源: https://codeday.me/bug/20191001/1840431.html


版权声明:本文为weixin_42398050原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。