【问题标题】:Java Switch hitting two cases [duplicate]Java Switch遇到两种情况[重复]
【发布时间】:2015-06-24 13:53:52
【问题描述】:

我正在尝试使用要处理的切换案例来处理组合用户输入,并且在最终切换之前似乎进展顺利

    System.out.println("\t output switch =  " + state.get(2));
    switch(state.get(2)){
        //Case MCNP
        case 0:
        {
            abundances = verifyAndNorm(abundances, new MCNPVerifier(MCNP));
            out = toMCNP(mat, abundances);
            System.out.println("\t MCNP");
        }

        //Case SCALE
        case 1:
        {
            abundances = verifyAndNorm(abundances, new SCALEVerifier(SCALE));
            out = toSCALE(mat, abundances, weightFracFlag);
            System.out.println("\t SCALE");
        }
    }       

打印出来

 output switch =  0
 MCNP
 SCALE

结果是 out = toScale(...),因为它同时打印 MCNP 和 SCALE,所以它必须同时满足两种情况,但它只适用于一种情况...

我在这里错过了什么?

【问题讨论】:

  • 这里发生了所谓的fall-through
  • 在我生命周期的这一点上,我希望不要被视为初学者,谦虚但仍然不好玩。

标签: java switch-statement


【解决方案1】:

为每个案例添加中断语句

System.out.println("\t output switch =  " + state.get(2));
switch(state.get(2)){
    //Case MCNP
    case 0:
    {
        abundances = verifyAndNorm(abundances, new MCNPVerifier(MCNP));
        out = toMCNP(mat, abundances);
        System.out.println("\t MCNP");
        break;
    }

    //Case SCALE
    case 1:
    {
        abundances = verifyAndNorm(abundances, new SCALEVerifier(SCALE));
        out = toSCALE(mat, abundances, weightFracFlag);
        System.out.println("\t SCALE");
        break;
    }
    default:
}    

【讨论】:

  • 您不想在案例 2 上第二个 break 吗?
  • 好像有一个关于答案的比赛:p
  • 我迟到了 16 秒...删除我的重复帖子 :( :p
  • Switch case 看起来无害,但明确要求使其容易出错,为了可读性/可维护性,最好使用 if-else
  • 如果 0 和 1 是 state.get() 唯一可能的返回值,那么使用 if-else 可能比使用 switch 构造更好。但是如果有更多可能的值,那么 switch 结构是最好的。此外,OP 应该考虑让 state.get() 返回一个枚举,这将使 switch 构造更具可读性:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多