-1

How to use && in the case of the switch? I want to convert this if-else into switch-case. Please help me I tried many options but didn't work any of them.

if( bpay <= 90000 &&  bpay >= 85000 )
{
System.out.println("You Job is General Manager");
}

if( bpay <= 84999 && bpay >= 75000 )
{
 System.out.println("Your Job is Manager" );
}

if ( bpay <= 74999 && bpay >= 65000 )
{
System.out.println("Your Job is Assistant Manager ");
}
if ( bpay <= 64999 && bpay >= 55000 )
{
System.out.println("Your Job is Accoutant");
}
if( bpay <= 54999 && bpay >= 40000 )
{
System.out.println("Your Job is Clerk");
}
if( bpay < 40000 )
System.out.println("You Job is Security Incharge");
Minhaa
  • 1

4 Answers4

1

That's not possible in Java. Switch was designed to identify unique cases.

P.S - Since, you're working with android, try Kotlin. You can achieve it in kotlin using when (basically switch but with superpowers). For eg:

when(bpay) {
  in 40000..55000 -> println("Your Job is Clerk")
  in 55000..65000 -> println("Your Job is Accoutant")
  //Similarly for the rest
}
Chrisvin Jem
  • 3,940
  • 1
  • 8
  • 24
1

You can't. This is not supported by the Java language. It may work in others, but not here. Cases must be an integer, string, or enum. THey are not boolean statements

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

Switch-case doesn't work on range, rather, it works on exact matches or constant values.

So, you can't convert this to switch-case, you have to use if-else here

touhid udoy
  • 4,005
  • 2
  • 18
  • 31
0

As said, that is not possible. Instead use if-else-if:

if ( bpay <= 90000 &&  bpay >= 85000 ) {
    System.out.println("You Job is General Manager");
} else if( bpay <= 84999 && bpay >= 75000 ) {
    System.out.println("Your Job is Manager" );
} else if ( bpay <= 74999 && bpay >= 65000 ) {
    System.out.println("Your Job is Assistant Manager ");
} else if ( bpay <= 64999 && bpay >= 55000 ) {
    System.out.println("Your Job is Accoutant");
} else if( bpay <= 54999 && bpay >= 40000 ) {
    System.out.println("Your Job is Clerk");
} else if( bpay < 40000 ) {
    System.out.println("You Job is Security Incharge");
}
Nurbol
  • 371
  • 2
  • 8