在我的代码中,程序根据用户输入的文本执行一些操作。我的代码如下:

switch (name) {
        case text1: {
            //blah
            break;
        }
        case text2: {
            //blah
            break;
        }
        case text3: {
            //blah
            break;
        }
        case text4: {
            //blah
            break;
        }

但是,案例text1和text4中的代码是相同的。因此,我想知道是否有可能让我实现一些像

case text1||text4: {
            //blah
            break;
        }

我知道||操作符在case语句中不起作用,但是否有类似的东西我可以使用。


当前回答

Java 12及以上版本

switch (name) {
    case text1, text4 -> // do something ;
    case text2, text3, text 5 -> // do something else ;
    default -> // default case ;
}

你也可以通过switch case表达式来赋值:

String text = switch (name) {
    case text1, text4 -> "hello" ;
    case text2, text3, text5 -> "world" ;
    default -> "goodbye";
};

“产量”关键字

它允许您通过开关大小写表达式返回一个值

String text = switch (name) {
    case text1, text4 ->
        yield "hello";
    case text2, text3, text5 ->
        yield "world";
    default ->
        yield "goodbye";
};

其他回答

括号是不必要的。只做

case text1:
case text4:
  doSomethingHere();
  break;
case text2:
  doSomethingElse()
  break;

如果有人好奇的话,这就是所谓的案件败诉。能做到这一点,就是为什么要打破;用于结束case语句。欲了解更多信息,请参阅维基百科文章http://en.wikipedia.org/wiki/Switch_statement。

case值只是可以共享相同入口点的无代码“goto”点:

case text1:
case text4: 
    //blah
    break;

注意,花括号是多余的。

只做

case text1: case text4: 
     do stuff;
     break;

case值只是可以共享相同入口点的无代码“goto”点:

案例text1: Case text4: { / /做某事 打破; }

注意,花括号是多余的。

一个switch语句可以使用多个case:

case "firstCase":
case "secondCase": {
    // Run code here for both cases
}