本文介绍了在switch语句中,为什么所有的case都被执行了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码和我从这个 ,它工作得非常好:

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

这篇关于在switch语句中,为什么所有的case都被执行了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:06