如何在Java中使用动态值调用枚举方法

时间:2018-06-30 17:37:48

标签: java multidimensional-array enums

我正在开发一个程序,我必须找到一个机器人在网格中的位置,它可以向前移动,并且可以将其面向北,南,东和西的方向更改,并已获得给定的命令顺序。那么,机器人的最终位置是什么。 禁止使用任何类型的条件分支(例如if / else,switch / case)。

示例-
网格-(100 * 500)
机器人的初始位置-(5,3)
可能的命令-
北北,
E-East,
W-West,
南南,
M向前移动
样本输入-{N,S,M.M,E,W,E,S,M,S,M}

我尝试使用Enum,但是我面临的问题是如何使用我通过命令获得的动态值调用Enum方法。

public class RobotMovesInGrid {
    Scanner input = new Scanner(System.in);
    String command=input.next();
    int commLength = command.length();

    static enum Command {
        N{@Override public void execute(String g, String r){ System.out.println("do the N move here"); }},
        E{@Override public void execute(String g, String r){ System.out.println("do the E move here"); }},
        S{@Override public void execute(String g, String r){ System.out.println("do the S move here"); }},
        W{@Override public void execute(String g, String r){ System.out.println("do the W move here"); }},
        M{@Override public void execute(String g, String r){ System.out.println("do the M move here"); }};
        public abstract void execute(String g, String r);

    }
    public void nextPosition() {
        Command c1;
        for(int i=0;i<commLength;i++) {
            if (command.charAt(i)=='N'||command.charAt(i)=='E'|| command.charAt(i)=='S'|| command.charAt(i)=='W'||command.charAt(i)=='M')

                c1= Command.M;// Here instead of M, I am trying to give dynamic commands but it is not taking it
            System.out.println("Current position is"+c1);
        }
    }
}

有人可以建议我如何使用作为输入的命令调用Enum方法。

4 个答案:

答案 0 :(得分:2)

这是另一种解决方案。

    static enum Command {
        N(-1,0),E(0,1),W(0,-1),S(1,0);
        private int rowIncrement;
        private int colIncrement;

        private Command(int rowIncrement, int colIncrement)
        {
            this.rowIncrement = rowIncrement;
            this.colIncrement = colIncrement;
        }

        public int getRowIncrement()
        {
            return rowIncrement;
        }

        public int getColIncrement()
        {
            return colIncrement;
        }
    }

这是命令评估的代码。

    //input
    String command = "NSMMEWESMSM";
    int[] pos = new int[]{5,3};
    int[] size = new int[]{100, 500};

    char[] chars = command.toCharArray();
    //replace M by the previous char, ie move in the same direction
    for (int i = 0; i < chars.length; i++)
    {
        char dir = chars[i];
        //this assumes that M cannot be the first char
        if (dir == 'M')
        {
            dir = chars[i-1];
            chars[i] = dir;
        }
    }


    for (char dir : chars)
    {
        Command cmd = Command.valueOf(String.valueOf(dir));
        pos[0] += cmd.rowIncrement;
        //row is within the region
        pos[0] = Math.min(Math.max(pos[0], 0), size[0] -1);

        pos[1] += cmd.colIncrement;
        //col is within the region
        pos[1] = Math.min(Math.max(pos[1], 0), size[1] -1);
    }

答案 1 :(得分:1)

最简单的方法是将输入char转换为String,然后调用枚举的valueOf(String)方法来检索枚举,例如:

for(int i=0;i<commLength;i++) {
   Command command = Command.valueOf(String.valueOf(command.charAt(i))
                                           .toUpperCase());
   if (command != null){
       command.execute(...);
   }
}

它可以工作,但我认为您的枚举值实际上没有任何意义。
您应该根据它们的含义重命名它们,使用包含映射字符的构造函数来丰富枚举类,并引入一个静态方法来检索与输入字符关联的枚举值:

static enum Command {
    NORTH('N'){@Override public void execute(String g, String r){ System.out.println("do the N move here"); }},
    EAST('E'){@Override public void execute(String g, String r){ System.out.println("do the E move here"); }},
    SOUTH('S'){@Override public void execute(String g, String r){ System.out.println("do the S move here"); }},
    WEST('W'){@Override public void execute(String g, String r){ System.out.println("do the W move here"); }},
    MOVE_FORWARD('M'){@Override public void execute(String g, String r){ System.out.println("do the M move here"); }};

    private char mappingChar;

    Command (char mappingChar){
        this.mappingChar = mappingChar;
    }

    public abstract void execute(String g, String r);

    public static Optional<Command> getFrom(char mappingChar) {
        for (Command command : values()) {
            if (Character.toUpperCase(mappingChar)==command.mappingChar) {
                return Optional.of(command);
            }
        }
        return Optional.empty();
    }
}

您现在可以动态检索枚举值并使用它:

for(int i=0;i<commLength;i++) {
    Optional<Command> optCommand = Command.getFrom(command.charAt(i)); 
    if (optCommand.isPresent()){
        optCommand.get().execute(...)
    }

    // or alternatively 
    optCommand.ifPresent(c -> c.execute(...));        
}

答案 2 :(得分:1)

一种实现方法是在内部类Map中使用恒定的静态enum Commands;它将StringCommands相关联。 Command.parse在地图中查找命令。

import java.lang.String;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.function.Function;
import java.awt.Point;
import java.util.Scanner;

class Robot {

    public static void main(String args[]) {
        try(Scanner input = new Scanner(System.in)) {
            input.useDelimiter(",\\s*|\n");
            Robot r = new Robot();
            while(input.hasNext()) {
                try {
                    Command.parse(input.next().trim()).apply(r);
                } catch(NullPointerException e) {
                    System.out.printf("Syntax error.\n");
                } catch(RuntimeException e) {
                    System.out.printf("Can't go that way: %s.\n",
                        e.getMessage());
                }
            }
        } catch(Exception e) {
            System.err.printf("%s: %s.\n", e, e.getMessage());
        }
    }

    Point x;
    static Point dim;
    Command last;

    Robot() {
        dim = new Point(100, 500);
        x = new Point(5, 3);
    }

    enum Command {
        N("N", "north",  true,  (r) -> new Point(r.x.x, r.x.y - 1)),
        E("E", "east",   true,  (r) -> new Point(r.x.x + 1, r.x.y)),
        S("S", "south",  true,  (r) -> new Point(r.x.x, r.x.y + 1)),
        W("W", "west",   true,  (r) -> new Point(r.x.x - 1, r.x.y)),
        M("M", "farther",false, (r) -> r.last != null ?r.last.go.apply(r):null);

        private String command, name;
        private boolean isDir;
        private Function<Robot, Point> go;
        private static final Map<String, Command> map;

        /* Map for turning commands into Directions; mod->const map. */
        static {
            Map<String, Command> mod = new HashMap<>();
            for(Command c : values()) mod.put(c.command, c);
            map = Collections.unmodifiableMap(mod);
        }

        /** Called from definition of enum. */
        private Command(final String command, final String name, boolean isDir,
            final Function<Robot, Point> go) {
            this.command = command;
            this.name    = name;
            this.isDir   = isDir;
            this.go      = go;
        }

        /** @param str A string representing the direction.
         @return The command or null. */
        public static Command parse(final String str) { return map.get(str); }

        /** Applies this command to r. */
        public void apply(Robot r) {
            Point x = this.go.apply(r);
            if(x == null)
                throw new RuntimeException("don't have a direction");
            if(x.x < 0 || x.x >= dim.x || x.y < 0 || x.y >= dim.y)
                throw new RuntimeException("at the edge");
            r.x = x;
            if(this.isDir == true) r.last = this;
            System.out.printf("Went %s to (%d, %d).\n", r.last.name, x.x, x.y);
        }

        /** @return The name of the direction. */
        public String toString() { return name; }
    }

}

它以EOF结尾。我发现这些有帮助,

答案 3 :(得分:0)

您可以使用Command.valueOf()

喜欢

c1 = Command.valueOf(command.toUpperCase());

这会将c1设置为与输入命令相对应的Command枚举值。

toUpperCase()确保其与枚举名称相同。