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"?
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.