Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Why switch statement in not comparing the int values?

**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 !");
        }
    }
}```
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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ä?" ); 
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda