Java 在 switch 中使用关系运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19269714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:35:13  来源:igfitidea点击:

use relational operators in switch

javaoperatorsswitch-statementrelational

提问by dabe

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

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

采纳答案by Aniket Kulkarni

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 booleanand 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.

  • No two of the case constant expressions associated with a switch statement may have the same value.

  • No switch label is null.

  • At most one default label may be associated with the same switch statement.

  • 与 switch 语句关联的每个 case 常量表达式都必须可分配(第 5.2 节)到 switch 表达式的类型。

  • 与 switch 语句关联的两个 case 常量表达式不能具有相同的值。

  • 没有开关标签为空。

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

回答by Aneesh

It will never work. You should understand what switchdoes in the first place.

它永远不会奏效。你应该首先了解什么是什么switch

It will execute the statements falling under the case which matches the switch argument.

它将执行符合 switch 参数的情况下的语句。

In this case, scoreis an argument which is 95but score>=90will always evaluate to either trueor falseand never matches an integer.

在这种情况下,score是一个参数,95score>=90将始终计算为trueorfalse并且从不匹配整数。

You should use ifstatements instead.

您应该改用if语句。

Also Java doesn't allow booleansin switch cases so yea.

Java 也不允许booleans在 switch 情况下,所以是的。

回答by Suresh Atta

Simply NO

简单NO

int score = 95;

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

You are passing a intvalue to switch. So the case's must be in intvalues, where

您正在将int值传递给switch. 所以案例必须在int值中,其中

(score >= 90)

Turns boolean.

boolean

Your case is a good candidaate for if else

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

回答by harsh

Unfortunately NO, though you can use casefall (kind of hacky) by grouping multiple case statements without breakand implement code when a range ends:

不幸的是 NO,尽管您可以case通过将多个 case 语句分组而不使用break并在范围结束时实现代码来使用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 ifwould be more appropriate in your particular case.

恕我直言,if在您的特定情况下使用更合适。

回答by A4L

The docs for switch-casestatement 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: trueor false.

所以没有布尔值。这样做没有任何意义,因为您只有两个值:true或 false。

What you could do is write a method which checks the score and then returns a one of the types switchcan 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, elsedirectly!

... 或者你可以直接使用if, else-if, else

回答by siledh

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

Switchaccepts any value to switch on and then provides functionality to match over boolean conditions (ifTruemethod) or by exact matches (ifEqualsmethod). Providing a value to switch on is needed just for the latter feature.

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

After building the conditions, user invokes getResultto 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

回答by Akhil Raj

This might help you if you need to do it with switch itself,

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

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