Reputation: 25
I was wondering if its possible to check for a range of numbers when doing a switch statement (switching an int). Like case: 1 - 50: // code.
Would this be possible instead of writing every case? Thanks.
Upvotes: 2
Views: 831
Reputation: 1328
If the question aims at ranges (like groovy supports), without having to list every item, the answer is: unfortunately not. Such a broad range would be implemented using an if, instead of a switch. Details to usage of switch
can be found in the Java Tutorial.
Upvotes: 4
Reputation: 21004
Yes you can, simply ommit the break
of the ancestor case
int test = 1;
switch(test)
{
case 0:
case 1:
case 2:
System.out.println("test");
break;
}
This won't print test
unless test
is equal to 0, 1 or 2
.
However, I don't see any point in doing this when you can do
if(integer >= 10 && integer <= 50)
Edit : I think I misunderstood this question, if the question was actually to know if it is possible to specify a range using only one case
keyword like
case 1-50:
break;
Then no, it is not possible, but once again, you can simply use the if
. Now you have answer to both possibilities of your question.
Upvotes: 0
Reputation: 978
Yes we can achieve that with a trick, see bellow:
int my_number = 30;
int switcher = my_number;
if (my_number >= 1 && my_number <= 50)
switcher = 1;
switch (switcher)
{
case 1:
// My number is in range 1 - 50
return true;
case 51:
// My number is not in range of 1 - 50.
return false;
}
Upvotes: 0
Reputation: 1411
The quick answer is no. You have specific cases within a switch statement that allows the code execution to have logic. Unless you specify all cases that need to be handled, the code execution will proceed to the default case which is not what you want.
The question I would as you is why would you want to? It is most definitely possible. You can you a switch statement where you have a case for every integer 1-50, and if the integer falls under this range, the corresponding case will execute.
With that being said, this is not the way this should be handled. The proper way to handle a situation like this is with an if statement: if (x >= 1 && x <= 50)
...
Upvotes: 0
Reputation: 8955
As @martin's answer, you cannot do it in the switch. But I think you can abstract a new case list according to this kind of requirement. e.g:
CASE_1: x>1 && x<50
CASE_2: x>50 && x < 100
...
You can define a function to convert the case before you use the switch.
Upvotes: 0