Java 在 switch 中使用关系运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19269714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use relational operators in switch
提问by dabe
Is there a way to use relational operators (<,<=,>,>=) in a switch statement?
有没有办法在 switch 语句中使用关系运算符(<、<=、>、>=)?
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
the above example (obviously) doesn't work
上面的例子(显然)不起作用
采纳答案by Aniket Kulkarni
No you can not.
From jls-14.11
你不能。
从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.
Relational operators (<,<=,>,>=) results in boolean
and which is not allowded.
关系运算符 (<,<=,>,>=) 导致boolean
和 不允许。
All of the following must be true, or a compile-time error occurs:
以下所有条件都必须为真,否则会发生编译时错误:
Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
No two of the case constant expressions associated with a switch statement may have the same value.
No switch label is null.
At most one default label may be associated with the same switch statement.
与 switch 语句关联的每个 case 常量表达式都必须可分配(第 5.2 节)到 switch 表达式的类型。
与 switch 语句关联的两个 case 常量表达式不能具有相同的值。
没有开关标签为空。
最多一个默认标签可以与同一个 switch 语句相关联。
回答by Aneesh
It will never work. You should understand what switch
does in the first place.
它永远不会奏效。你应该首先了解什么是什么switch
。
It will execute the statements falling under the case which matches the switch argument.
它将执行符合 switch 参数的情况下的语句。
In this case, score
is an argument which is 95
but score>=90
will always evaluate to either true
or false
and never matches an integer.
在这种情况下,score
是一个参数,95
但score>=90
将始终计算为true
orfalse
并且从不匹配整数。
You should use if
statements instead.
您应该改用if
语句。
Also Java doesn't allow booleans
in switch cases so yea.
Java 也不允许booleans
在 switch 情况下,所以是的。
回答by Suresh Atta
Simply NO
简单NO
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
You are passing a int
value to switch
. So the case's must be in int
values, where
您正在将int
值传递给switch
. 所以案例必须在int
值中,其中
(score >= 90)
Turns boolean
.
转boolean
。
Your case is a good candidaate for if else
你的案子是一个很好的候选人 if else
回答by harsh
Unfortunately NO, though you can use case
fall (kind of hacky) by grouping multiple case statements without break
and implement code when a range ends:
不幸的是 NO,尽管您可以case
通过将多个 case 语句分组而不使用break
并在范围结束时实现代码来使用fall (有点hacky):
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;
}
IMHO, using if
would be more appropriate in your particular case.
恕我直言,if
在您的特定情况下使用更合适。
回答by A4L
The docs for switch-casestatement state:
switch-case语句状态的文档:
a switch statement tests expressions based only on a single integer, enumerated value, or String object.
switch 语句仅基于单个整数、枚举值或 String 对象测试表达式。
So there is no boolean. Doing so would make no sence since you only have two values: true
or false.
所以没有布尔值。这样做没有任何意义,因为您只有两个值:true
或 false。
What you could do is write a method which checks the score and then returns a one of the types switch
can handle
你可以做的是编写一个方法来检查分数,然后返回一个switch
可以处理的类型
For example:
例如:
enum CheckScore {
SCORE_HIGHER_EQUAL_90,
...
}
public CheckScore checkScore(int score) {
if(score >= 90) {
return SCORE_HIGHER_EQUAL_90;
} else if(...) {
return ...
}
}
and then use it in your switch:
然后在您的交换机中使用它:
switch(checkScore(score)) {
case SCORE_HIGHER_EQUAL_90:
// do stuff
}
... Or You could just use if, else-if, else
directly!
... 或者你可以直接使用if, else-if, else
!
回答by siledh
Obviously, this is not possible as a language construct. But, just for fun, we could implement it by ourselves!
显然,这作为语言结构是不可能的。但是,为了好玩,我们可以自己实现它!
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
accepts any value to switch on and then provides functionality to match over boolean conditions (ifTrue
method) or by exact matches (ifEquals
method). Providing a value to switch on is needed just for the latter feature.
Switch
接受任何要打开的值,然后提供匹配布尔条件(ifTrue
方法)或精确匹配(ifEquals
方法)的功能。只需要为后一个功能提供一个值来打开。
After building the conditions, user invokes getResult
to obtain the result.
建立条件后,用户调用getResult
以获取结果。
For example, we could create a method that tells us what it thinks about our score:
例如,我们可以创建一个方法来告诉我们它对我们的分数的看法:
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();
}
This simple test:
这个简单的测试:
for (int score : new int[] { 97, 85, 66, 55, 42, 32, 4 }) {
System.out.println(score + ": " + tellMeMyScore(score));
}
Prints out:
打印出来:
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
回答by Akhil Raj
This might help you if you need to do it with switch itself,
如果您需要使用 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);
It works this way,
它是这样工作的,
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';