in JavaScript and also I've seen it in PHP : You can use a logical expression inside you cases : For Example :
switch(true){
case (d<10):
document.write("Less than 10");
break;
case (d==10):
document.write("Equal to 10");
break;
case (d>10):
document.write("Greater than 10");
break;
default:
document.write("Some dumb error. Probably not a number.");
}
I was wondering if we can do this in Java ... say I needed a to pare a very large range.
case 1 :
case 2 :
...
case 5000:
case 5001:
default:
It would be tedious to do. I could wrap my cases inside if statements but i was wondering it could be done like in JavaScript or PHP.
in JavaScript and also I've seen it in PHP : You can use a logical expression inside you cases : For Example :
switch(true){
case (d<10):
document.write("Less than 10");
break;
case (d==10):
document.write("Equal to 10");
break;
case (d>10):
document.write("Greater than 10");
break;
default:
document.write("Some dumb error. Probably not a number.");
}
I was wondering if we can do this in Java ... say I needed a to pare a very large range.
case 1 :
case 2 :
...
case 5000:
case 5001:
default:
It would be tedious to do. I could wrap my cases inside if statements but i was wondering it could be done like in JavaScript or PHP.
Share Improve this question asked May 14, 2013 at 2:05 hayonjhayonj 1,4493 gold badges21 silver badges29 bronze badges 3-
Side note: I don't believe that you can write such
switch
/case
in JavaScript MDN. – Alexei Levenkov Commented May 14, 2013 at 2:11 - @AlexeiLevenkov Switch/case works flawlessly in JavaScript. – Tdorno Commented May 14, 2013 at 2:22
- @Tdorno that is insane... but you are absolutely right... thanks. – Alexei Levenkov Commented May 14, 2013 at 2:26
2 Answers
Reset to default 3It is nice to have, but you cannot. Quoting JLS:
The body of a switch statement is known as a switch block.
Any statement immediately contained by the switch block may be labeled with one or more switch labels, which are case or default labels.
These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) or enum constants (§8.9.1) in the case labels.
These labels have to be constant expressions or enum constants
.
No You cannot do that using switch in java. You have to use if-else
to acplish this.
See this link for more details.