How can I convert the following code to switch statement?
String x = "user input";
if (x.contains("A")) {
//condition A;
} else if (x.contains("B")) {
//condition B;
} else if(x.contains("C")) {
//condition C;
} else {
//condition D;
}
There is a way, but not using contains
. You need a regex.
final Matcher m = Pattern.compile("[ABCD]").matcher("aoeuaAaoe");
if (m.find())
switch (m.group().charAt(0)) {
case 'A': break;
case 'B': break;
}