Java Switch 命中两个案例

标签 java switch-statement

<分区>

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

    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,所以它必须同时满足这两种情况,但它只适用于一种情况...

我在这里错过了什么?

最佳答案

为每个case添加break语句

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

关于Java Switch 命中两个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028548/

相关文章:

asp.net 移动/桌面站点切换按钮,切换主页,但样式 "stuck"

linux - 如何让switch执行2个case

java - Spring MVC 中的 Controller 和 Handler 有什么区别?

java - 模拟泊松等待时间

c# - WCF RESTful 服务的 Java 和其他客户端

java - Android 上的字符串转换和区域设置

java - 单个 java switch 语句返回 2 个变量

arrays - 当查找映射到小整数的常量时,使用 case 语句还是常量数组更快?

android - 如何压缩重复的 switch 语句

java - 在 ConstraintLayout 中将 View 置于另一个 View 之下