Java Switch遇到两种情况

时间:2015-06-24 13:53:53

标签: 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,它必须同时击中两种情况,但它只适用于一个......

我在这里缺少什么?

1 个答案:

答案 0 :(得分:9)

为每个案例添加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:
}