Java - switch case, Multiple cases call the same function

前端 未结 3 1557
陌清茗
陌清茗 2020-12-20 12:28

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

switch(str) {
// compiler error
case \"apple\", \"orange\", \"         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-20 13:00

    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;
    }
    

    Edit 02/05/2019

    Java 12

    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.

    Another syntax also is :

    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;
    }
    

    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();
    }
    

    Nice syntax

提交回复
热议问题