简体   繁体   English

switch case语句中的布尔逻辑 - Java

[英]Boolean logic in switch case statement - Java

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

What is the best way to do this in Java? 在Java中执行此操作的最佳方法是什么?

Of course. 当然。

Just use 只是用

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

OR if you have to use a switch statement, you can do it this way: 或者如果你必须使用switch语句,你可以这样做:

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

Basically, you can't really have multiple cases the way you had thought about it. 基本上,你不可能像你想象的那样拥有多个案例。 It's not the same structure as an if statement, where you can do various logical operations. 它与if语句的结构不同,您可以在其中执行各种逻辑操作。 Java does not go through and do an if statement for each of the cases. Java 经历和做的if语句为每一个案件。

Instead, each time you have case("foo") , Java sees this as something called a Case Label. 相反,每次有case("foo") ,Java都会将其视为一个名为Case Label的东西。 It is the reason that we sometimes opt to use switch statements, even though they are very primitive and sometimes not very convenient. 这是我们有时选择使用switch语句的原因,即使它们非常原始且有时不太方便。 Because we have case labels, the computer only has to do one evaluation, and it can jump to correct place and execute the right code. 因为我们有案例标签,所以计算机只需进行一次评估,它可以跳转到正确的位置并执行正确的代码。

Here is a quote from a website that may help you: 以下是可能对您有所帮助的网站的引用:

A switch statement, as it is most often used, has the form: 最常用的switch语句具有以下形式:

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 exactly the same effect as the following multiway if statement, but the switch statement can be more efficient because the computer can evaluate one expression and jump directly to the correct case, whereas in the if statement, the computer must evaluate up to N expressions before it knows which set of statements to execute: 这与以下multiway if语句具有完全相同的效果,但switch语句可以更高效,因为计算机可以计算一个表达式并直接跳转到正确的大小写,而在if语句中,计算机必须最多评估N个表达式在它知道要执行哪组语句之前:

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

yes you can do as: Fall through in swith case 是的,你可以这样做:在swith case Fall through

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM