在 switch 中使用关系运算符 [英] use relational operators in switch

查看:51
本文介绍了在 switch 中使用关系运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to use relational operators (<,<=,>,>=) in a switch statement?

int score = 95;

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

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

the above example (obviously) doesn't work

推荐答案

不,你不能.
来自 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,这是不允许的.

Relational operators (<,<=,>,>=) results in boolean and which is not allowded.

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

All of the following must be true, or a compile-time error occurs:

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

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

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

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

没有开关标签为空.

同一个switch语句最多可以关联一个默认标签.

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

这篇关于在 switch 中使用关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆