CodeCamper
CodeCamper

Reputation: 6980

Switch statement not working in Java with enum

I created an enum like so

public enum Direction {
    NORTH, SOUTH, WEST, EAST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
}

then I try to use it in a switch statement

 Direction direction = Direction.NORTH;
    switch(direction){
    NORTH:
        System.out.println("Syntax error on token {, case expected after this token");
        break;
    }

I am getting the error I put in the println...

Upvotes: 2

Views: 1071

Answers (2)

Mehul Lalan
Mehul Lalan

Reputation: 84

While not directly answering the question, I would suggest adding a method to the enum (Java Enum Methods) and calling the method instead. This would make it cleaner if and when we add a new enum type. We don't have to make modifications to the switch case, just add the implementation for the newly added enum type.

Upvotes: 3

riccardo.cardin
riccardo.cardin

Reputation: 8353

You miss the case keyword.

switch(direction){
case NORTH:
    System.out.println("Syntax error on token {, case expected after this token");
    break;
}

Demo

Upvotes: 5

Related Questions