Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use relational operators in switch

Is there a way to use relational operators (<,<=,>,>=) in a switch statement?

int score = 95;

switch(score)  {
   case (score >= 90):
      // do stuff
}

the above example (obviously) doesn't work

like image 385
qsi Avatar asked Oct 09 '13 10:10

qsi


3 Answers

No you can not.
From jls-14.11

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.  

Relational operators (<,<=,>,>=) results in boolean and which is not allowded.

All of the following must be true, or a compile-time error occurs:

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

  • No two of the case constant expressions associated with a switch statement may have the same value.

  • No switch label is null.

  • At most one default label may be associated with the same switch statement.

like image 156
Aniket Kulkarni Avatar answered Nov 19 '22 04:11

Aniket Kulkarni


This might help you if you need to do it with switch itself,

char g ='X';
            int marks = 65;
            switch(marks/10)
            {
                case 1:
                case 2:
                case 3:
                case 4: g = 'F';
                        break;
                case 5: g = 'E';
                        break;
                case 6: g = 'D';
                        break;
                case 7: g = 'C';
                        break;
                case 8: g = 'B';
                        break;
                case 9: 
                case 10: g = 'A';       
                         break;
            }
            System.out.println(g);

It works this way,

    if(marks<50)
                g='F';
            else if(marks<60)
                g='E';
            else if(marks<70)
                g='D';
            else if(marks<80)
                g='C';
            else if(marks<90)
                g='B';
            else if(marks<=100)
                g='A';
like image 20
Akhil Raj Avatar answered Nov 19 '22 06:11

Akhil Raj


Unfortunately NO, though you can use case fall (kind of hacky) by grouping multiple case statements without break and implement code when a range ends:

int score = 95;
switch(score) {
 ..
 case 79: System.out.println("value in 70-79 range"); break;
 case 80:
 ..
 case 85: System.out.println("value in 80-85 range"); break;
 case 90:
 case 91:
 case 92:
 case 93:
 case 94:
 case 95: System.out.println("value in 90-95 range"); break;
 default: break;
}

IMHO, using if would be more appropriate in your particular case.

like image 1
harsh Avatar answered Nov 19 '22 04:11

harsh