use relational operators in switch(在 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 中使用关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 switch 中使用关系运算符
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
