Why do dis not work
i wont an switch case with yield. But it not compile
userColor is input from user. Data type String
String animalColor = switch (userColor) {
case "green" -> {
if (animal.equals("Frog")) yield "Frog";
}
case "yellow" -> {
yield "Budgie";
}
case "pink" -> {
yield "Pig";
}
case "brown" -> {
yield "Cow";
}
case "black" -> {
yield "Panther";
}
case "white" -> {
yield "Mouse";
}
case "white/black" -> {
yield animal;
}
case "gold" -> {
yield "Goldfish";
}
default -> {
yield "Unknown";
}
};
Her how it look if it frog or orca…
String animal = "";
if (Objects.equals(userColor, "green")) {
System.out.println("Do you mean Frog");
String isFrog = myObj.nextLine(); // Read user input
isFrog = isFrog.toLowerCase(Locale.ROOT);
if (Objects.equals(isFrog, "yes")) {
animal = "Frog";
}
} else if (Objects.equals(userColor, "white/black")) {
while (true) {
System.out.println("Do you mean Orca or Zebra");
String isOrcaOrZebra = myObj.nextLine(); // Read user input
isOrcaOrZebra = isOrcaOrZebra.toLowerCase(Locale.ROOT);
if (Objects.equals(isOrcaOrZebra, "orca")) {
animal = "Orca";
break;
} else if (Objects.equals(isOrcaOrZebra, "zebra")) {
animal = "Zebra";
break;
} else {
System.out.println("Type Orca or Zebra");
}
}
}
But that compile easy
All compile but case not.
it says:
Switch expression rule should produce result in all execution paths
thanks for help
>Solution :
You can also so
String animalColor = switch (userColor) {
case "green" -> {
if (animal.equals("Frog")) yield "Frog";
yield "";
}
case "yellow" -> {
yield "Budgie";
}
case "pink" -> {
yield "Pig";
}
case "brown" -> {
yield "Cow";
}
case "black" -> {
yield "Panther";
}
case "white" -> {
yield "Mouse";
}
case "white/black" -> {
yield animal;
}
case "gold" -> {
yield "Goldfish";
}
default -> {
yield "Unknown";
}
};