This question already has answers here:
Switch executes all case statements
                                
                                    (2个答案)
                                
                        
                                4年前关闭。
            
                    
我正在尝试将组合用户输入与要处理的切换用例一起处理,直到最终切换为止似乎一切顺利

    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,因此必须同时满足这两种情况,但这仅适用于一种情况...

我在这里想念什么?

最佳答案

在每种情况下添加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:
}

08-16 22:27