Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - switch statement with range of int

I want to use a switch statement to check a range of numbers I have found a few places saying something like case 1...5 or case (score >= 120) && (score <=125) would work but I just somehow keep on getting errors.

What I want is if the number is between 1600-1699 then do something.

I can do if statements but figured it's time to start using switch if possible.

like image 276
WXR Avatar asked Mar 06 '15 05:03

WXR


People also ask

Can switch case have range in Java?

Case ranges and case labels can be freely intermixed, and multiple case ranges can be specified within a switch statement.

Can switch case have a range of values?

Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

Can you use switch statement with int?

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte , short , char , and int primitive data types.

How do you use a range of a number switch?

Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.


1 Answers

You can use ternary operator, ? :

int num = (score >= 120) && (score <=125) ? 1 : -1;
num = (score >= 1600) && (score <=1699 ) ? 2 : num;
switch (num) {
    case 1 :
       break;
    case 2 :
       break;
    default :
      //for -1
}
like image 99
akash Avatar answered Nov 06 '22 04:11

akash