Java - switch case, Multiple cases call the same function

前端 未结 3 1555
陌清茗
陌清茗 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

    0 讨论(0)
  • 2020-12-20 13:05

    You got error because you used comma between case queries. To define multiple cases, you have to use semi colon so like this.

    switch (str) {
    case "orange": case "pineapple": case "apple":
         handleFruit();
         break;
    }
    
    0 讨论(0)
  • 2020-12-20 13:09

    Java supports fall-through when you have no break:

    case "apple":
    case "orange":
    case "pieapple":
        handleFruit();
        break;
    
    0 讨论(0)
提交回复
热议问题