2

I'm not sure how to get round it.

Need help with details please

AbarthGT
  • 49
  • 1
  • 8

3 Answers3

2

You first create a Map<String, Shape>, containing all the possible commands as keys, and the corresponding shape as value:

Map<String, Shape> shapesByCommand = new HashMap<String, Shape>();
shapesByCommand.put("circle", new Circle());
shapesByCommand.put("sun", new Sun());
...

Then, when you receive the command, you get the corresponding shape and make it visible:

Shape shape = shapesByCommand.get(commands[0]);
if (shape != null && "visible".equals(commands[1])) {
    makeVisible(shape);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

I think JB Nizet' answer will probably help you, especially for the first part of your problem. However, if you are after a general solution for the second part of your question, namely how to call a function based on a string that you want to look up in a HashMap, what you probably want to do is store function objects in that HashMap, and then call that function object after the lookup (you may also find this discussion helpful).

Here's an example (using Strings rather than Shapes):

public interface Action {
    abstract void run(String s);
}

public static void main(String[] args) {
    HashMap<String, Action> actions = new HashMap<String, Action>();
    actions.put("visible", new Action() {
        public void run(String s) {
            System.out.println("Running 'visible' on: " + s);
        }
    });
    String input[];
    input = new String[2];
    input[0] = "sun";
    input[1] = "visible";
    actions.get(input[1]).run(input[0]);
}

Output: Running 'visible' on: sun

Community
  • 1
  • 1
m01
  • 9,033
  • 6
  • 32
  • 58
0

I wouldn't use a HashMap here, I would use an EnumMap

Then, in the code of your enum, you could put all the implementations as methods of the various enum subclasses.

public enum Actions {
  visible, move, resize;

  public doAction(Shape s) {
    switch(this) {
      case visible:
        // handle command
        break;
      case move:
        // etc.
  }
}

public enum ShapeEnum {
  circle, sun, square;
}

Then, in your code, you can do:

 try {
   Actions a = Actions.valueOf(command);
   Shapes s = Shapes.valueOf(shape);

   a.doCommand(myEnumMap.get(s));
 } catch (IllegalArgumentException e) {
   // not a command, handle it
 }
durron597
  • 31,968
  • 17
  • 99
  • 158