Boolean logic in a switch statement expression - Java

 switch (i) {
     case ("+" || "/"):  
        setOperator("i");
        break;
 }

      

What's the best way to do this in Java?

+3


source to share


3 answers


Sure.

Just use

if(i.equals("+") || i.equals("/")) {
    setOperator("i");
}

      

OR, if you need to use a switch statement, you can do it like this:

switch(i) {
    case "+":
    case "/":
        setOperator("i");
        break;
}

      

Basically, you cannot have multiple cases the way you thought about it. It is not the same structure as an if statement, where you can perform various logical operations. Java does not execute and does an if statement for each case.



Instead, every time you have it case("foo")

, Java sees it as something called an event label. This is the reason why we sometimes prefer to use switch statements, although they are very primitive and sometimes not very convenient. Since we have the cue labels, the computer only needs to do one evaluation and it can navigate to the right place and execute the correct code.

Here's a quote from the website that might help you:

The switch statement, as it is most often used, has the form:

switch (expression) {
   case constant-1:
      statements-1
      break;
   case constant-2:
      statements-2
      break;
      .
      .   // (more cases)
      .
   case constant-N:
      statements-N
      break;
   default:  // optional default case
      statements-(N+1)
} // end of switch statement

      

This has the same effect as the following multiway if statement, but a switch statement can be more efficient because the computer can evaluate one expression and jump directly to the correct case, whereas in an if statement, the computer must evaluate up to N expressions before it knows which set of operators to execute:

if (expression == constant-1) { // but use .equals for String!!
    statements-2
} 
else if (expression == constant-2) { 
    statements-3
} 
else
    .
    .
    .
else if (expression == constant-N) { 
    statements-N
} 
else {
    statements-(N+1)
}

      

+16


source


yes you can do like this: Fall through

inswith case



      switch (i) {
        case "+":
        case "/":
            setOperator(i);
            break;
      }

      

+1


source


switch (i) {
    case ("+"):
    case ("/"):
        setOperator("i");
        break;
    }

      

+1


source







All Articles