Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a switch statement, why are all the cases being executed?

I have this code with the switch statement which I got from this post, and it works absolutely fine:

String getOrdinal(final int day) {
    if (day >= 11 && day <= 13) {
        return "th";
    }
    switch (day % 10) {
        case 1: return "st";
        case 2: return "nd";
        case 3: return "rd";
        default: return "th";
    }
}

But if I change it to something like the following, it breaks, as all the cases besides case 1 gets executed:

  static String getOrdinal(final int day) {
    StringBuilder ordinalBuilder = new StringBuilder();
    ordinalBuilder.append("<sup>");
    if (day >= 11 && day <= 13) {
        ordinalBuilder.append("th") ;
    }
    switch (day % 10) {
        case 1: ordinalBuilder.append("st");
        case 2: ordinalBuilder.append("nd");
        case 3: ordinalBuilder.append("rd");
        default: ordinalBuilder.append("th");
    }
    ordinalBuilder.append("</sup>");
   return ordinalBuilder.toString();
 }

This prints 2<sup>ndrdth</sup> when I pass in 2. I tried changing the builder to buffer but I got the same response... Could this be a bug or am I making some mistake?

like image 562
Hell Boy Avatar asked Nov 09 '11 00:11

Hell Boy


People also ask

Does switch statement execute all cases?

The switch statement evaluates its expression, then executes all statements that follow the matching case label. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

Which cases of a switch statement are executed?

The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed.

How is a switch statement executed?

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, === ) and transfers control to that clause, executing all statements following that clause.

How many cases can you have in a switch statement?

You can use it as many as you like, but it is not a good thing, as your code will become long and boring, this can be avoided by using loops, functions, or several other methods.


1 Answers

It's a bug in your code. You forgot to put in a break after each case:

switch (day % 10) {
    case 1: ordinalBuilder.append("st"); break;
    case 2: ordinalBuilder.append("nd"); break;
    case 3: ordinalBuilder.append("rd"); break;
    default: ordinalBuilder.append("th"); break;
}
like image 173
CanSpice Avatar answered Nov 11 '22 01:11

CanSpice