So I've been assigned the task of making a program to move an object around a string map in java. I've been asked to use an enum with a specific char via fileresource to command movement via the ObjCommand enum.
This is what I've got so far as far as basics..., but I keep spinning my wheels in trying different things and now I am all muddled up.
so here goes -
public enum ObjCommand {
FORWARD (F),
TURN_LEFT(L),
TURN_RIGHT(R),
(Other commands...);
public char directionKey;
private ObjCommand(char directionKey){
this.directionKey = directionKey;
}
//public char getDirectionKey() {
// return DirectionKey
public final char getDirectionKey(char directionKey){
return directionKey;
}
....I'm trying to throw in different methods such as toString, etc, which I know I'll need, but the chars(F, L, etc) just seem to not want to register as a variable and now I'm just totally confused.
I'm still learning and any help would be appreciated :)
I'm sure I'm not explaining myself properly, so here is the uml for this specific part just in case it can add any clarity to what I am trying to do here:
enum ObjCommand <<enumeration>>
FORWARD : F
TURN_LEFT : L
TURN_RIGHT : R
(etc. other moves by key entry) then:
- ObjCommand(directionKey : char)
getDirectionKey() : char
I appreciate anybody who takes the time to look at this and help a total n00b out. This part of it is driving me a little bonkers :)
CodePudding user response:
Maybe you can check this and compare to your code:
https://www.baeldung.com/java-enum-values
2nd:
Shouldn't your chars be in quotes?
FORWARD ('F'),
and a getter should not take a inpout parameter.
CodePudding user response:
In terms of getting you started with enums, you can access them via the enum name like so:
ObjCommand.TURN_LEFT
If you'd like to access via the single character strings, you can write a static function like so:
static ObjCommand getFromChar(char c) {
switch (c) {
case 'F':
return ObjCommand.FORWARD;
case 'L':
return ObjCommand.TURN_LEFT;
case 'R':
return ObjCommand.TURN_RIGHT;
default:
throw new IllegalArgumentException("Invalid command character " c);
}
}
Also, concerning getDirectionKey
, your current version just returns whatever value is passed in, so it has nothing to do with the enum value. It's likely what you really want is a final
field directionKey
and a getter that returns its value:
public char getDirectionKey() {
return this.directionKey;
}
CodePudding user response:
Your Enum could look like this:
public enum ObjCommand {
FORWARD('F');
private final char key;
private ObjCommand(char key) {
this.key = key;
}
public char getDirectionKey() {
return key;
}
}
With getDirectionKey
you would retrieve your key.