Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda