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 中使用关系运算符
基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
