Wednesday 25 December 2019

java - How to match and switch Strings against enums?




I want to transform a String into an enum. But how?



class Letter {
A, B, C
}

String letter = "A";
switch (letter) {
case Letter.A: //cannot convert from Letter to String

case Letter.A.toString(): //case expressions must be constant expressions
case Letter.C.name(): //case expressions must be constant expressions
default:
}

Answer



First the Letter must be an enum:



enum Letter {
A, B, C

}

Letter letter = Letter.valueOf("A")
// and just switch
switch (letter) {
case A:
case B:
case C:
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...