可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
In Java is it possible to write a switch statement where each case contains more than one value? For example (though clearly the following code won\'t work):
switch (num) {
case 1 .. 5:
System.out.println(\"testing case 1 to 5\");
break;
case 6 .. 10:
System.out.println(\"testing case 6 to 10\");
break;
}
I think this can be done in Objective C, are there a similar thing in Java? Or should I just use if
, else if
statements instead?
回答1:
Java has nothing of that sort. Why not just do the following?
public static boolean isBetween(int x, int lower, int upper) {
return lower <= x && x <= upper;
}
if (isBetween(num, 1, 5)) {
System.out.println(\"testing case 1 to 5\");
} else if (isBetween(num, 6, 10)) {
System.out.println(\"testing case 6 to 10\");
}
回答2:
The closest you can get to that kind of behavior with switch
statements is
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println(\"1 through 5\");
break;
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println(\"6 through 10\");
break;
}
Use if
statements.
回答3:
other alternative is using math operation by dividing it, for example:
switch ((int) num/10) {
case 1:
System.out.println(\"10-19\");
break;
case 2:
System.out.println(\"20-29\");
break;
case 3:
System.out.println(\"30-39\");
break;
case 4:
System.out.println(\"40-49\");
break;
default:
break;
}
But, as you can see this can only be used when the range is fixed in each case.
回答4:
I don\'t think you can do that in Java. Best bet is to just put the code in the last case of the range.
switch (num) {
case 1: case 2: case 3: case 4: case 5:
System.Out.Println(\"testing case 1 to 5\");
break;
case 6: case 7: case 8: case 9: case 10:
System.Out.Println(\"testing case 6 to 10\");
break;
default:
//
}
回答5:
case 1: case 2: case 3: case 4: case 5:
System.out.println(\"testing case 1 to 5\");
break;
case 6: case 7: case 8: case 9: case 10:
System.out.println(\"testing case 6 to 10\");
break;
default:
System.out.println(\"default\");
回答6:
No you can\'t do that. The best you can do is that
case 1:
case 2:
case 3:
case 4:
case 5:
System.Out.Println(\"testing case 1 to 5\");
break;
回答7:
Try this if you must use switch.
public static int range(int num){
if ( 10 < num && num < 20)
return 1;
if ( 20 <= num && num < 30)
return 2;
return 3;
}
public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;
public static void main(String[]args){
int a = 110;
switch (range(a)){
case TEN_TWENTY:
System.out.println(\"10-20\");
break;
case TWENTY_THIRTY:
System.out.println(\"20-30\");
break;
default: break;
}
}
回答8:
It\'s possible to group several conditions in the same case
statement using the mechanism of fall through allowed by switch statements, it\'s mentioned in the Java tutorial and fully specified in section §14.11. The switch Statement of the Java Language Specification.
The following snippet of code was taken from an example in the tutorial, it calculates the number of days in each month (numbered from month 1 to month 12):
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println(\"Invalid month.\");
break;
}
As you can see, for covering a range of values in a single case
statement the only alternative is to list each of the possible values individually, one after the other. As an additional example, here\'s how to implement the pseudocode in the question:
switch(num) {
case 1: case 2: case 3: case 4: case 5:
System.out.println(\"testing case 1 to 5\");
break;
case 6: case 7: case 8: case 9: case 10:
System.out.println(\"testing case 6 to 10\");
break;
}
回答9:
I know this post is old but I believe this answer deserves some recognition. There is no need to avoid the switch statement. This can be done in java but through the switch statement, not the cases. It involves using ternary operators.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
switch ((1 <= num && num <= 5 ) ? 0 :
(6 <= num && num <= 10) ? 1 : 2) {
case 0:
System.out.println(\"I\'m between one and five inclusive.\");
break;
case 1:
System.out.println(\"I\'m between 6 and 10 inclusive.\");
break;
case 2:
System.out.println(\"I\'m not between one and five or 6 and 10 inclusive.\");
break;
}
}
}
回答10:
You could use an enum
to represent your ranges,
public static enum IntRange {
ONE_TO_FIVE, SIX_TO_TEN;
public boolean isInRange(int v) {
switch (this) {
case ONE_TO_FIVE:
return (v >= 1 && v <= 5);
case SIX_TO_TEN:
return (v >= 6 && v <= 10);
}
return false;
}
public static IntRange getValue(int v) {
if (v >= 1 && v <= 5) {
return ONE_TO_FIVE;
} else if (v >= 6 && v <= 10) {
return SIX_TO_TEN;
}
return null;
}
}
回答11:
Or you could use your solo cases as intended and use your default case to specify range instructions as :
switch(n) {
case 1 : System.out.println(\"case 1\"); break;
case 4 : System.out.println(\"case 4\"); break;
case 99 : System.out.println(\"case 99\"); break;
default :
if (n >= 10 && n <= 15)
System.out.println(\"10-15 range\");
else if (n >= 100 && n <= 200)
System.out.println(\"100-200 range\");
else
System.out.println(\"Your default case\");
break;
}
回答12:
Use a NavigableMap
implementation, like TreeMap
.
/* Setup */
NavigableMap<Integer, Optional<String>> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, Optional.empty());
messages.put(1, Optional.of(\"testing case 1 to 5\"));
messages.put(6, Optional.of(\"testing case 6 to 10\"));
messages.put(11, Optional.empty());
/* Use */
messages.floorEntry(3).getValue().ifPresent(System.out::println);
回答13:
@missingfaktor \'s answer is indeed correct but a bit over-complicated.
Code is more verbose (at least for continuous intervals) then it could be, and requires overloads/casts and/or parameterization for long, float, Integer etc
if (num < 1)
System.Out.Println(\"invalid case: \" + num); // you should verify that anyway
else if (num <= 5)
System.Out.Println(\"1 to 5\");
else if (num <= 10)
System.Out.Println(\"6 to 10\");
else if (num <= 42)
System.Out.Println(\"11 to 42\");
else
System.Out.Println(\"43 to +infinity\");
回答14:
Here is a beautiful and minimalist way to go
(num > 1 && num < 5) ? first_case_method()
: System.out.println(\"testing case 1 to 5\")
: (num > 5 && num < 7) ? System.out.println(\"testing case 1 to 5\")
: (num > 7 && num < 8) ? System.out.println(\"testing case 1 to 5\")
: (num > 8 && num < 9) ? System.out.println(\"testing case 1 to 5\")
: ...
: System.out.println(\"default\");