As already stated before, you have to add break;
statements for each case
if you want to stop at that special one. Your code would then look like this:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
}
}
Another thing you really should do is adding a default
case for any non matching input (imagine someone input "Hy"
instead of "Hi"
, there wouldn't be any output for that...):
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\" or \"Bye\" instead!");
}
}
The default
statement is an option for anything that isn't handled in the case
statements.
Now back to the break
s... You can handle different case
s just the same if you set the breaks only to some of the case
s:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
case "Hy":
System.out.println("Hi");
break;
case "Bye":
case "By":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\", \"Hy\", \"By\" or \"Bye\" instead!");
}
}
Doing like this, you will receive the same output for "Hi"
and "Hy"
without duplicating the code that handles both case
s.