有没有办法在 switch 语句中使用关系运算符 (<,<=,>,>=)?
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
上面的例子(显然)不起作用
不,你不能。
来自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 语句最多只能关联一个默认标签。
如果你需要用 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';
不幸的是没有,虽然你可以使用
case
fall(有点hacky)通过在没有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
在您的特定情况下会更合适。
永远行不通。您应该首先了解
switch
的作用。
它将执行符合 switch 参数的 case 语句。
在这种情况下,
score
是一个参数,它是 95
但 score>=90
将始终评估为 true
或 false
并且永远不会匹配整数。
您应该改用
if
语句。
此外,Java 不允许
booleans
在 switch 案例中,是的。
简单NO
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
您正在将
int
值传递给 switch
。所以案例的必须是int
值,其中
(score >= 90)
转
boolean
.
你的案子很适合
if else
switch-case 语句状态的文档:
switch 语句仅基于单个整数、枚举值或字符串对象测试表达式。
所以没有布尔值。这样做没有任何意义,因为您只有两个值:
true
或 false。
你可以做的是编写一个方法来检查分数,然后返回一个
switch
可以处理的类型
例如:
enum CheckScore {
SCORE_HIGHER_EQUAL_90,
...
}
public CheckScore checkScore(int score) {
if(score >= 90) {
return SCORE_HIGHER_EQUAL_90;
} else if(...) {
return ...
}
}
然后在你的开关中使用它:
switch(checkScore(score)) {
case SCORE_HIGHER_EQUAL_90:
// do stuff
}
... 或者你可以直接使用
if, else-if, else
!
显然,这作为一种语言结构是不可能的。但是,为了好玩,我们可以自己实现它!
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
如果关系运算符不起作用,那么使它们起作用的唯一方法是擦除关系运算符并手动输入单词。
例如:
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...
}