In the switch statement, why is everything done?

I have this code with a switch statement that I got from a message that 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 this, it will break, since all cases except case 1 are 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 go to '2', I tried changing the builder to a buffer, but the same answer .. maybe this is an error or am I mistaken?

+4
source share
5 answers

This is a mistake in your code. You forgot to put 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; } 
+33
source

I do not see any error here, at least not how the language works. The design behavior of the switch is that it starts executing statements on the case label that matches the argument, and then continues to the end of the block. So

 switch (x) { case 1: // do thing 1 case 2: // do thing 2 case 3: // do thing 3 default: // do nothing } 

will do both things 2 and 3 if x is 2, and will do things 1, 2 and 3 if x is 1.

To get the behavior you're probably looking for, run each case with break :

 switch (x) { case 1: // do thing 1 break; case 2: // do thing 2 break; case 3: // do thing 3 break; default: // do nothing break; } 

(strictly speaking, break at the very end is not necessary, but I often put it out of habit).

The reason you didn’t have this problem in the first code example is because return looks like a super- break : it has the same effect as break , namely, completing execution in the switch block, but also completing everything method.

+18
source

you need to add a break statement in each switch case. It worked earlier because you made a return from the method ...

+9
source

Operator "break;" separates cases from each other, so to execute statements in a particular case, just interrupt the register as soon as it ends.

If you do not use break, the compiler believes that it can continue to execute all cases until the end of the program.

+6
source

The first version will return before continuing in the case statement. The second version needs a break; statement to get the same behavior.

+3
source

Source: https://habr.com/ru/post/1380302/


All Articles