2

I'm trying to handle combinatoric user input with switch cases to process, and it seemed to be going well until the final switch

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

Prints out

 output switch =  0
 MCNP
 SCALE

And the result is that out = toScale(...), and since it is printing both MCNP and SCALE, it must be hitting both cases, but it's only true for one...

What am I missing here?

Captain Prinny
  • 459
  • 8
  • 23

1 Answers1

9

add break statements to each case

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:
}    
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
  • Don't you want a second `break` on case 2? – Zizouz212 Jun 24 '15 at 13:55
  • 1
    Like there is a race on the answer :p – Danielson Jun 24 '15 at 13:56
  • 2
    I was 16 seconds late... Deleting my duplicate post :( :p – Danielson Jun 24 '15 at 14:02
  • I think we have all made this mistake many times :) – James Wierzba Jun 24 '15 at 14:03
  • 1
    Switch case looks harmless but explicit requirement of makes it error prone, it is better to use if-else for readability/maintainability for sake – Ashkrit Sharma Jun 24 '15 at 14:17
  • 1
    If 0 and 1 are the only possible return values of state.get(), then using if-else is probably better than using a switch construct. But if there are many more possible value, the switch construct is best. Also the OP should consider having state.get() return an enum, which would make the switch construct more readable: – FredK Jun 24 '15 at 14:55
  • Literally realized this as I left for a meeting. And there are baseline of 3 cases possible, more with anticipated scope creep. Enuming is probably a good idea, though I hadn't considered it as I could have just passed a string of IDs from the calling buttons and that seemed to heavy handed on locking in the UI naming conventions that would be prone to explosion later, but it's a project in the works. – Captain Prinny Jun 24 '15 at 15:00