**I wrote a simple code that have to compare to numbers, but when I run it compiler say me that has a error with boolean values. I dont understand why it doesnt work **
{
public static void main(String[] args) {
compare(8,22);
}
static void compare(int a, int b){
switch (a) {
case (a > b) -> System.out.println(a + " > " + b);
case (b < a) -> System.out.println(a + " < " + b);
case (a == b) -> System.out.println(a + " = " + b);
default -> System.out.println("Something is wrong !");
}
}
}```
Change it to:
{
public static void main( String... args )
{
compare( 8, 22 );
}
static void compare( final int a, final int b )
{
switch( Integer.signum( Integer.compare( a, b ) ) )
{
case 1 -> System.out.println( a + " > " + b );
case -1 -> System.out.println( a + " < " + b );
case 0 -> System.out.println( a + " = " + b );
default -> System.out.println( "Something is wrong !" );
}
}
}
And it should work!
case requires distinct constant expressions, and the terms that you use ((a > b), (b < a) and (a == b)) are no constants (not to mention that (a > b) and (b < a) are equivalent). They also return a boolean. switch does not handle a boolean switch selector directly.
In JShell, (only) this works for switch with "boolean":
boolean flag = …
switch( Boolean.toString( flag ) )
{
case "true" -> …
case "false" -> …
default -> throw new Error( "Hä?" );
}