在switch语句中使用关系运算符

6

有没有办法在 switch 语句中使用关系运算符(<,<=,>,>=)?

int score = 95;

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

上述示例(显然)无法正常运行。

8个回答

13

不,你不能这样做。
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类型,不允许使用。

以下所有条件必须都满足,否则会在编译时出错:

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

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

  • 没有switch标签为null。

  • 最多只能有一个default标签与同一switch语句相关联。


3

如果您需要在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);

这是它的工作原理。
    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';

2
这个已经很多年了,但如果你看到这条评论,请问这是如何/为什么工作的? - MagicGAT

1
很不幸,虽然你可以使用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;
}

在我看来,对于你的特定情况,使用if会更合适。

0

绝对不行

int score = 95;

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

你正在将一个 int 值传递给 switch。因此,case 必须是 int 值,其中

(score >= 90)

boolean 转换。

你的情况很适合使用 if else


0

switch-case文档声明:

switch语句仅基于单个整数、枚举值或字符串对象测试表达式。

因此没有布尔值。这样做没有意义,因为你只有两个值:truefalse

你可以编写一个检查分数并返回switch可处理类型之一的方法。

例如:

enum CheckScore {
    SCORE_HIGHER_EQUAL_90,
    ...
}


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

然后在你的switch语句中使用它:

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

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


0

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

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

0

这样是行不通的。你应该首先了解 switch 的作用。

switch 会执行与匹配 switch 参数的 case 相关的语句。

在这种情况下,score 是一个参数,它的值为 95,但是 score>=90 只会评估为 truefalse,永远不会匹配一个整数。

你应该使用 if 语句代替。

此外,Java 不允许在 switch case 中使用 booleans


0
如果关系运算符不起作用,那么使它们起作用的唯一方法就是手动删除关系运算符并手动输入单词。
例如:
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...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接