**Escribí un código simple que tengo que comparar con números, pero cuando ejecuto el compilador me dice que tiene un error con los valores booleanos. No entiendo por qué no funciona **
{ 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 !"); } } }```cambiarlo a:
{ 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 !" ); } } }¡Y debería funcionar!
El case requiere expresiones constantes distintas, y los términos que usa ( (a > b) , (b < a) y (a == b) ) no son constantes (sin mencionar que (a > b) y (b < a) son equivalentes). También devuelven un valor booleano. switch no maneja un selector de interruptor booleano directamente.
En JShell, (solo) esto funciona para switch con "boolean":
boolean flag = … switch( Boolean.toString( flag ) ) { case "true" -> … case "false" -> … default -> throw new Error( "Hä?" ); }