Java-切换大小写,多个大小写调用同一函数 [英] Java - switch case, Multiple cases call the same function

查看:40
本文介绍了Java-切换大小写,多个大小写调用同一函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我有多个应该以相同方式处理的 String 案例,所以我尝试:

Since I have multiple String cases which should be handled the same way, I tried:

switch(str) {
// compiler error
case "apple", "orange", "pieapple":
  handleFruit();
  break;
}

但是出现编译器错误.

在Java中,我必须逐个调用相同的函数:

Should I have to, in Java, call the same function case by case:

switch(str) {
  case "apple":
      handleFruit();
       break;
  // repeat above thing for each fruit
  ...
}

没有更简单的风格吗?

推荐答案

对于每个这样的String,您都必须使用 case 关键字:

You have to use case keyword for each String like this :

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开始,提出了新的switch case语法,因此要解决此问题,方法如下:

From Java 12 there are a new syntax of switch case proposed, so to solve this issue, here is the way:

switch (str) {
    case "apple", "orange", "pieapple" -> handleFruit();
}

现在,您可以选择多个选项,并用逗号分隔,用箭头-> 分隔,然后选择要执行的操作.

Now, you can just make the choices separated by comma, the an arrow -> then the action you want to do.

另一种语法也是:

考虑到每种情况都返回一个值,并且您想在变量中设置值,假设 handleFruit()返回一个 String ,旧语法应为:

consider that each case return a value, and you want to set values in a variable, lets suppose that handleFruit() return a String the old syntax should be :

String result;  //  <-------------------------- declare 
switch (str) {
    //which mean if String equals to
    case "apple":      // apple
    case "orange":     // or orange
    case "pieapple":   // or pieapple
        result = handleFruit();  //      <----- then assign
        break;
}

现在使用Java 12,您可以像这样:

now with Java 12, you can make it like this :

String result = switch (str) { //  <----------- declare and assign in one shot
    case "apple", "orange", "pieapple" -> handleFruit();
}

不错的语法

这篇关于Java-切换大小写,多个大小写调用同一函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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