代码之家  ›  专栏  ›  技术社区  ›  qsi

在交换机中使用关系运算符

  •  6
  • qsi  · 技术社区  · 11 年前

    有没有一种方法可以在switch语句中使用关系运算符(<,<=,>,>=)?

    int score = 95;
    
    switch(score)  {
       case (score >= 90):
          // do stuff
    }
    

    上面的例子(显然)不起作用

    8 回复  |  直到 11 年前
        1
  •  13
  •   Aniket Kulkarni    11 年前

    不,你不能。
    从…起 jls-14.11

    The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.  
    

    关系运算符(<,<=,>,>!=)导致 boolean 并且这是不允许的。

    以下所有条件必须为true,否则将发生编译时错误:

    • 与switch语句相关的每个case常量表达式都必须可赋值(§5.2)给switch表达式的类型。

    • 与switch语句关联的大小写常量表达式中没有两个可以具有相同的值。

    • 没有开关标签为空。

    • 最多可以有一个默认标签与同一个switch语句相关联。

        2
  •  3
  •   Akhil Raj    9 年前

    如果您需要使用交换机本身,这可能会对您有所帮助,

    char g ='X';
                int marks = 65;
                switch(marks/10)
                {
                    case 1:
                    case 2:
                    case 3:
                    case 4: g = 'F';
                            break;
                    case 5: g = 'E';
                            break;
                    case 6: g = 'D';
                            break;
                    case 7: g = 'C';
                            break;
                    case 8: g = 'B';
                            break;
                    case 9: 
                    case 10: g = 'A';       
                             break;
                }
                System.out.println(g);
    

    它是这样工作的,

        if(marks<50)
                    g='F';
                else if(marks<60)
                    g='E';
                else if(marks<70)
                    g='D';
                else if(marks<80)
                    g='C';
                else if(marks<90)
                    g='B';
                else if(marks<=100)
                    g='A';
    
        3
  •  1
  •   harsh    11 年前

    不幸的是没有 ,尽管您可以使用 case fall(有点技巧)通过将多个case语句分组而没有 break 并在范围结束时实现代码:

    int score = 95;
    switch(score) {
     ..
     case 79: System.out.println("value in 70-79 range"); break;
     case 80:
     ..
     case 85: System.out.println("value in 80-85 range"); break;
     case 90:
     case 91:
     case 92:
     case 93:
     case 94:
     case 95: System.out.println("value in 90-95 range"); break;
     default: break;
    }
    

    IMHO,使用 if 在你的特殊情况下会更合适。

        4
  •  0
  •   Aneesh    11 年前

    它永远不会起作用。你应该明白 switch 首先是这样。

    它将执行与switch参数匹配的case下的语句。

    在这种情况下, score 是一个论点 95 但是 score>=90 将始终评估为 true false 并且从不与整数匹配。

    你应该使用 if 取而代之的是语句。

    此外,Java不允许 booleans 在切换的情况下也是如此。

        5
  •  0
  •   Suresh Atta    11 年前

    仅仅

    int score = 95;
    
    switch(score)  {
       case (score >= 90):
          // do stuff
    }
    

    你正在通过 int 值到 switch 。所以这个案子一定在里面 整数 值,其中

    (score >= 90)
    

    转动 boolean .

    你的案子是一个很好的候选人 if else

        6
  •  0
  •   A4L    11 年前

    这个 docs for switch-case 语句状态:

    switch语句只基于单个整数、枚举值或String对象测试表达式。

    所以没有布尔值。这样做毫无意义,因为您只有两个值: true 或错误。

    你可以做的是编写一个方法,检查分数,然后返回其中一个类型 switch 可以处理

    例如:

    enum CheckScore {
        SCORE_HIGHER_EQUAL_90,
        ...
    }
    
    
    public CheckScore checkScore(int score) {
        if(score >= 90) {
            return SCORE_HIGHER_EQUAL_90;
        } else if(...) {
            return ...
        }
    }
    

    然后在交换机中使用:

    switch(checkScore(score))  {
       case SCORE_HIGHER_EQUAL_90:
          // do stuff
    }
    

    …或者你可以用 if, else-if, else 直接地

        7
  •  0
  •   siledh    11 年前

    显然,作为一种语言结构,这是不可能的。但是,只是为了好玩,我们可以自己实现它!

    public class Switch<T, V> {
    
        public static interface Action<V> {
            V run();
        }
    
        private final T value;
        private boolean runAction = false;
        private boolean completed = false;
        private Action<V> actionToRun;
    
        public Switch(T value) {
            this.value = value;
        }
    
        static public <T, V> Switch<T, V> on(T value) {
            return new Switch<T, V>(value);
        }
    
        public Switch<T, V> ifTrue(boolean condition) {
            runAction |= condition;
            return this;
        }
    
        public Switch<T, V> ifEquals(T other) {
            return ifTrue(value.equals(other));
        }
    
        public Switch<T, V> byDefault(Action<V> action) {
            this.actionToRun = action;
            return this;
        }
    
        public Switch<T, V> then(Action<V> action) {
            if (runAction && !completed) {
                actionToRun = action;
                completed = true;
            }
            return this;
        }
    
        public V getResult() {
            if (actionToRun == null) {
                throw new IllegalStateException("none of conditions matched and no default action was provided");
            }
            return actionToRun.run();
        }
    }
    

    Switch 接受任何要打开的值,然后提供匹配布尔条件的功能( ifTrue 方法)或通过精确匹配( ifEquals 方法)。只需要为后一个功能提供一个可打开的值。

    建立条件后,用户调用 getResult 以获得结果。

    例如,我们可以创建一种方法,告诉它对分数的看法:

    String tellMeMyScore(int score) {
        return Switch.<Integer, String> on(score).byDefault(new Action<String>() {
            public String run() {
                return "really poor score";
            }
        }).ifTrue(score > 95).then(new Action<String>() {
            public String run() {
                return "you rock!";
            }
        }).ifTrue(score > 65).then(new Action<String>() {
            public String run() {
                return "not bad, not bad";
            }
        }).ifEquals(42).then(new Action<String>() {
            public String run() {
                return "that's the answer!";
            }
        }).getResult();
    }
    

    这个简单的测试:

    for (int score : new int[] { 97, 85, 66, 55, 42, 32, 4 }) {
        System.out.println(score + ": " + tellMeMyScore(score));
    }
    

    打印输出:

    97: you rock!
    85: not bad, not bad
    66: not bad, not bad
    55: really poor score
    42: that's the answer!
    32: really poor score
    4: really poor score
    
        8
  •  0
  •   Eric Aya    2 年前

    如果关系运算符不起作用,那么使它们起作用的唯一方法就是删除关系运算符并手动输入单词。

    例如:

    System.out.println("Enter your grade: ");
    int grade=kb.nextInt();
    
    switch(grade) {
         case (80 | 81 | 82 | 83 | 84 | 85):
           System.out.println("LOW GRADES");
         case (86 | 87 | 88 | 89 | 90 | 91 | 92 | 93):
           System.out.println("AVERAGE GRADES");
        //so on, and so for until 100...
    }