C++有一个很方便的switch语句,但不知道这是否可能是java
switch(num)
{
case 1 ... 9:
do something
break
case 10 ... 19:
do something
break
default: something
}
这在java中是否可行,我试过了,但它不起作用,至少不像c ++那样,有没有等价物?
谢谢
C++有一个很方便的switch语句,但不知道这是否可能是java
switch(num)
{
case 1 ... 9:
do something
break
case 10 ... 19:
do something
break
default: something
}
这在java中是否可行,我试过了,但它不起作用,至少不像c ++那样,有没有等价物?
谢谢
Java's switch
statement requires you to explicitly list all values that you match (except for the default:
clause, of course). If you're doing substantial ranges, it is probably better to use a chain of if
s:
if (num >= 1 && num <= 9) {
do_something_A
} else if (num >= 10 && num <= 19) {
do_something_B
} else {
do_something_C
}
If your real num
has side effects (or is plain expensive to compute), evaluate it once and save it to a local variable, then use that local in the chain of tests.
No, it's not possible. Probably the most straightforward equivalent is:
if (num >= 1 && num <= 9)
doSomething();
else if (num >= 10 && num <= 19)
doSomethingElse();
else
doDefault();
Marginal cleanup could be defining an inRange
utility function and using it inside the if
statements:
boolean inRange(int num, int min, int max) {
return num >= min && num <= max;
}
...
if (inRange(num, 1, 9))
doSomething();
else if (inRange(num, 10, 19))
doSomethingElse();
else
doDefault();
Java have switch statement, but you have to use it in this way :
switch(num)
{
case 1:
case 2:
case 3:
case 4:
//And so far with cases
//do something
break
case 10:
case 11:
case 12:
//And so far ...
//do something
break
default: something
}
Yes, there is a switch
statement in Java. It is in fact quite similar to switch
in C++.
However, neither C++ nor Java support ranges in case labels.
For the specific example that you present I would use a series of if
statements:
if (num >= 1 && num <= 9) {
...
} else if (num >= 10 && num <= 19) {
...
} else {
...
}
没有 Java 不会,在这种情况下,使用一系列 if-else 语句会更实用。:)
if(num >= 1 && num < 10) {
//do something
} else if(num >= 10 && num < 20) {
//do something
} else {
//do something
}
您正在谈论的功能实际上并不属于 C++,它是一种语言扩展,例如存在于 GCC 中。但通常在 C++ 范围内使用if
...检查else
,并且在 Java 中应该使用相同的技术:
if (num >= 1 && num <= 9) {
//Do something
} else if (num >= 10 && num <= 19) {
//Do something else
} else {
//Do something by default
}
No, ranges are not allowed you would need to use an if else structure.