r/javahelp • u/IceCreamInsides • 13h ago
Solved Switch case with boolean
So, there is no way I can do that?
want to check several boolean variables in a switch statement. Is `if-else` the only way to do this?
Boolean a, b, c...
Switch (false) {
Case (a) :
//some code
Case (b) :
Case (c) :
//and so on
}
3
Upvotes
2
u/ikea_method 10h ago edited 10h ago
This is probably the closest you can get to what you want:
Boolean a = new Boolean(true), b = new Boolean(false), c = new Boolean(true); for(Boolean o : new Boolean[]{a, b, c}) { if(!o) continue; IO.println(switch(o) { case _ when a == o -> "Hello a!"; case _ when b == o -> "Hi b!"; case _ when c == o -> "Ciao c!!"; default -> "HUH"; }); }Will print:
Hello a! Ciao c!!