简体   繁体   English

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

[英]use relational operators in switch

Is there a way to use relational operators (<,<=,>,>=) in a switch statement? 有没有办法在switch语句中使用关系运算符(<,<=,>,> =)?

int score = 95;

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

the above example (obviously) doesn't work 上面的例子(显然)不起作用

No you can not. 你不能。
From jls-14.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.  

Relational operators (<,<=,>,>=) results in boolean and which is not allowded. 关系运算符(<,<=,>,> =)导致boolean ,并且不允许。

All of the following must be true, or a compile-time error occurs: 必须满足以下所有条件,否则会发生编译时错误:

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression. 与switch语句关联的每个case常量表达式必须可分配(第5.2节)到switch表达式的类型。

  • No two of the case constant expressions associated with a switch statement may have the same value. 与switch语句关联的两个case常量表达式中没有两个可能具有相同的值。

  • No switch label is null. 没有开关标签为空。

  • At most one default label may be associated with the same switch statement. 最多一个默认标签可以与同一个switch语句相关联。

This might help you if you need to do it with switch itself, 如果您需要使用交换机本身,这可能会有所帮助,

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

It works this way, 它以这种方式工作,

    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';

Unfortunately NO , though you can use case fall (kind of hacky) by grouping multiple case statements without break and implement code when a range ends: 不幸的是 ,虽然你可以通过将多个case语句分组而没有break并在范围结束时实现代码来使用case fall(hacky):

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, using if would be more appropriate in your particular case. 恕我直言,使用if在您的特定情况下会更合适。

It will never work. 它永远不会奏效。 You should understand what switch does in the first place. 你应该首先了解switch作用。

It will execute the statements falling under the case which matches the switch argument. 它将执行与switch参数匹配的语句。

In this case, score is an argument which is 95 but score>=90 will always evaluate to either true or false and never matches an integer. 在这种情况下, score是一个参数,它是95score>=90将始终评估为truefalse并且从不匹配整数。

You should use if statements instead. 您应该使用if语句。

Also Java doesn't allow booleans in switch cases so yea. Java也不允许在交换机情况下使用booleans

Simply NO 没有

int score = 95;

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

You are passing a int value to switch . 您正在传递一个int值来switch So the case's must be in int values, where 所以案例必须是int值,其中

(score >= 90)

Turns boolean . 转动boolean

Your case is a good candidaate for if else 你的情况是一个很好的candidaate的if else

The docs for switch-case statement state: switch-case语句状态的文档

a switch statement tests expressions based only on a single integer, enumerated value, or String object. switch语句仅根据单个整数,枚举值或String对象测试表达式。

So there is no boolean. 所以没有布尔值。 Doing so would make no sence since you only have two values: true or false. 这样做不会产生任何意义,因为您只有两个值: true或false。

What you could do is write a method which checks the score and then returns a one of the types switch can handle 你可以做的是编写一个方法来检查分数,然后返回一个switch可以处理的类型

For example: 例如:

enum CheckScore {
    SCORE_HIGHER_EQUAL_90,
    ...
}


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

and then use it in your switch: 然后在你的交换机中使用它:

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

... Or You could just use if, else-if, else directly! ...或者您可以直接使用if, else-if, else

Obviously, this is not possible as a language construct. 显然,这不可能作为一种语言结构。 But, just for fun, we could implement it by ourselves! 但是,只是为了好玩,我们可以自己实现它!

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 accepts any value to switch on and then provides functionality to match over boolean conditions ( ifTrue method) or by exact matches ( ifEquals method). Switch接受任何值以打开,然后提供匹配布尔条件( ifTrue方法)或完全匹配( ifEquals方法)的功能。 Providing a value to switch on is needed just for the latter feature. 仅为后一特征需要提供接通值。

After building the conditions, user invokes getResult to obtain the result. 构建条件后,用户调用getResult来获取结果。

For example, we could create a method that tells us what it thinks about our score: 例如,我们可以创建一个方法来告诉我们它对我们得分的看法:

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

This simple test: 这个简单的测试:

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

Prints out: 打印出来:

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

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

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