26

在我使用任何编程语言的 1 个月经验中,我假设switch case条件会接受括号中的任何内容作为布尔检查 thingamajig,即:

|| && < >

明白我的意思了吗?

就像是

char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
    System.out.println ("W or w");
}

可悲的是,似乎并没有那样工作。我不能在开关盒中进行布尔检查。

有办法解决吗?

顺便说一句,如果我听起来令人困惑,非常抱歉。我还不太清楚这种语言中所有内容的名称:X
感谢任何答案

4

5 回答 5

57

对于这样的情况,您可以实现 OR:

switch (someChsr) {
case 'w':
case 'W':
    // some code for 'w' or 'W'
    break;
case 'x': // etc
}

案例就像一个“goto”,多个 goto 可以共享同一行来开始执行。

于 2012-12-08T04:25:23.950 回答
7

你可以做 -

switch(c) {
    case 'W':
    case 'w': //your code which will satisfy both cases
              break;

    // ....
}
于 2012-12-08T04:26:45.237 回答
4

每个 case 后面通常都有一个“break;”。指示执行应在何处终止的语句。如果省略“break;”,则继续执行。您可以使用它来支持应以相同方式处理的多种情况:

char someChar = 'w';
{
case 'W':
  // no break here
case 'w': 
  System.out.println ("W or w");
  break;
}
于 2012-12-08T04:26:16.047 回答
1

Switch case 是给定表达式的替代评估的分支。表达式在 switch 括号中给出,可以是 byte、short、char 和 int 数据类型。

switch 语句的主体称为 switch 块。switch 块中的语句可以用一个或多个 case 或默认标签进行标记。switch 语句计算其表达式,然后执行匹配 case 标签后面的所有语句。

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

于 2012-12-08T04:27:29.310 回答
0

对于 switch 语句的替代(多个 if 条件),我认为最好的解决方案是使用枚举。例如:考虑以下情况:-

    public enum EnumExample {

  OPTION1{

    public double execute() {
      Log.info(CLASS_NAME, "execute", "The is the first option.");
      return void;
    }

  },
  OPTION2{

    public double execute() {
      Log.info(CLASS_NAME, "execute", "The is the second option.");
      return void;
    }

  },
  OPTION3{

    public double execute() {
      Log.info(CLASS_NAME, "execute", "The is the third option.");
      return void;

  };

  public static final String CLASS_NAME = Indicator.class.getName();

  public abstract void execute();

}

上述枚举可以按以下方式使用:

EnumExample.OPTION1.execute();

希望这对你们有帮助。

于 2018-06-04T12:43:17.913 回答