In my code, the program does something depending on the text entered by the user. My code looks like:
switch (name) {
case text1: {
//blah
break;
}
case text2: {
//blah
break;
}
case text3: {
//blah
break;
}
case text4: {
//blah
break;
}
However, the code inside cases text1
and text4
is the same. I was therefore wondering if it would be possible for me to implement something like
case text1||text4: {
//blah
break;
}
I know that the ||
operator won't work in the case statement but is there something similar I can use.
Best Answer
You can use have both
CASE
statements as follows.SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:
This is the output from the code:
FALLTHROUGH:
EXAMPLE CODE:
This is the output from the code:
Using Strings in switch Statements
The output from this code is 8.
FROM Java Docs