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

195
Visualizações
How to have a switch case scenario using String as condition?

I have a String that I need to get the last digit from and use switch cases according to that character.

String securityNumber= "4561";
String lastDigit = securityNumber.substring(securityNumber.length()-1);

switch (lastDigit) {
    case "0": System.out.println("0");
        break;
    case "1": System.out.println("1");
        break;
    case "2": System.out.println("2");
        break;
    case "3": System.out.println("3");
        break;
    case "4": System.out.println("4");
        break;
    default: System.out.println("def");
}

I am getting the "def" as a result but should be "1".

What am I doing wrong? How can I have a case scenario for each of the digits from an input of String "securityNumber"?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need a break at the end of each case, otherwise the switch case will fall through and execute all the succeeding cases after the first one it matches. When I run it, it prints:

1 2 3 4 def

To fix this, here is the code:

String securityNumber = "4561";
String lastDigit = securityNumber.substring(securityNumber.length()-1);
switch (lastDigit) {
    case "0": System.out.println("0");
              break;
    case "1": System.out.println("1");
              break;
    case "2": System.out.println("2");
              break;
    case "3": System.out.println("3");
              break;
    case "4": System.out.println("4");
              break;
    default: System.out.println("def");
}

You also forgot a ; at the end of the declaration for securityNumber, so it might have not compiled.

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