-1

So I need to implement a switch statement that is used when given a command. The commands are like "end", or "B". However, one of the commands is setup like "S1" or "S6", the int after referring to a certain thing later in the program. Can I do a switch statement for all the other commands, and also the "S" + int one at the same time? Meaning it will go to that section of the switch statement that starts with "S", regardless of the number afterwards?

switch(command) {
    case "B":
        ....
        break;
    case "S" + %d (???):  // I know this won't work, just trying to convey the idea
        ....
        break;
}
Josh Newlin
  • 108
  • 2
  • 11

2 Answers2

1

Since Java 7, the case labels in a switch statement can be Strings. Of course, then the switch expression must also be a String. The case labels must be constant Strings, however, so nothing of the form "S" + %d (???) or anything much like it is supported.

If you only have one special case command to deal with, however, then perhaps you can handle it in the default case:

switch(command) {
    case "B":
        ....
        break;
    case "FOO":
        // ...
        break;
    default:
        if (command.startsWith("S")) {
            // ...
        } else {
            // whatever ...
        }
        break;
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

No. If this sort of switch is the correct way to go (and if often isn't; you may want to see how rich enums can help in this situation), then you might try this:

switch (command.charAt(0)) {
    case 'B':
        ....
        break;
    case 'S':
        switch (command.chatAt(1)) {
            case '0':
                ....
                break;
        }
        ....
        break;
}

Adding methods to enums, which will likely result in more readable application code in this situation, is explained in the Java tutorials. There's a few good examples here on Stack Overflow; check out the answers to this question.

As an example:

public enum CommandType {
    B {
        @Override
        public Object doStuff() {
            ...
        }
    },
    ...
    S1 {
        @Override
        public Object doStuff() {
            ...
        }
    },
    ...
    S6 {
        @Override
        public Object doStuff() {
            ...
        }
    }

    public abstract Object doStuff();
};

(Of course, you could put all the logic in the base doStuff() and forget about overriding it for each enum value, if that's better in your case.)

Then your application code can do something like

Enum.valueOf(CommandType.class, command).doStuff();
Community
  • 1
  • 1
Paul Hicks
  • 13,289
  • 5
  • 51
  • 78