在switch语句中,为什么所有的case都被执行了?

2022-01-19 00:00:00 switch-statement java

我有这个代码和我从这个 switch 语句ordinal-characters">post,它工作得非常好:

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";
    }
}

但如果我将其更改为类似以下的内容,它就会中断,因为除了 case 1 之外的所有情况都会被执行:

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();
 }

当我传入 2 时,这将打印 2.我尝试将构建器更改为缓冲区,但我得到了相同的响应......这可能是一个错误还是我犯了一些错误?

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?

推荐答案

这是您代码中的错误.你忘了在每个 case 后面加上一个 break:

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;
}

相关文章