Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
¿Por qué cambiar la declaración al no comparar los valores int?

**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 !"); } } }```
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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ä?" ); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!