-2

Why the default case always run?

public class HelloWorld {
    public enum ScenarioState {
        INIT,
        START,
        STOP,
        DESTROY
    }

    public static void displayRecord(ScenarioState state) {
        switch (state) {
            case INIT:
            case START:
            case STOP:
                System.out.println("1");
            default:
                System.out.println("default");
        }
    }

    public static void main(String[] args) {
        ScenarioState state = ScenarioState.INIT;
        displayRecord(state);
    }
}

The expected output should be

1

but the actual Output:

1
default

Why cause this problem? anyone can help me

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Alen Lee
  • 2,479
  • 2
  • 21
  • 30

3 Answers3

5

You need to add a break to all your switch-branches or you will experience what you are experiencing right now, called a fall-through.

Java will execute all statements starting from your matching case sequentially until it encounters the end of the switch or a break-statement.

In your case it seems actually want that fall-through for all your branches other than the default branch. So you would need to add a break at the end of your STOP case.

This would be the correct way to go:

switch (state)
{
    case INIT:
    case START:
    case STOP:
        System.out.println("1");
        break;
    default:
        System.out.println("default");
}
Ben
  • 1,665
  • 1
  • 11
  • 22
  • Could I ask why this is getting a downvote? Did I miss something? – Ben May 17 '18 at 08:37
  • Don't know, I was reading this question and thought that this answer was the most complete. Maybe due to answer a surely duplicated and low quality question? Anyway, this answer is the best of three and solves the question's author. Voted up – Marc Estrada May 17 '18 at 08:42
  • Some people probably think this simple problem should be a comment and not an answer. At least that's been my experience. But I disagree with that ;) – JoschJava May 17 '18 at 08:42
  • Thought same, but why the other answers doesn't has a down vote? – Marc Estrada May 17 '18 at 08:43
  • 3
    I downvoted, because the OP clearly expects `1` to be print out when switching on `INIT`. Which your answer doesn't allow anymore – Lino May 17 '18 at 08:45
  • Ah thanks for pointing that out. But why not just point it out to.. improve the answer? Well, I could improve the answer now, so still thanks a lot! – Ben May 17 '18 at 08:50
  • 1
    make an edit, an the downvote will be withdrawn. Because currently your answer is just *wrong* and missleading – Lino May 17 '18 at 08:51
  • 1
    I already did ;) – Ben May 17 '18 at 08:51
2

Add the break; statement to After your Case

Delly Fofie
  • 304
  • 2
  • 9
0

You need to add break; to the end of each case statement.

HamishD
  • 349
  • 2
  • 15