【发布时间】:2018-06-29 13:30:57
【问题描述】:
我面临一个问题,我必须找到一个机器人在网格中的位置,它可以向前移动,可以改变其朝向北、南、东和西的方向,并且已经提供了给定的命令序列.那么,机器人的最终位置将是什么。 禁止使用任何类型的条件分支(例如 if/else、switch/case)。
示例-
网格-(100*500)
机器人初始位置-(5,3)
可能的命令-
N-北,
东东,
西西,
南-南,
M-前进
样本输入-{N,S,M.M,E,W,E,S,M,S,M}
我的算法-
我在想我可以使用一个映射,其中我的键是命令,值将在该特定命令上执行。
但我不知道如何通过 HashMap 值调用函数。
我们还必须考虑网格不再有任何可能移动的最终情况。
我按照建议尝试了这段代码,但没有得到如何使用 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);
}
//return c1;
}
}
有人可以建议我如何使用作为输入的命令调用 Enum 方法。
【问题讨论】:
-
您应该制作功能接口图。 baeldung.com/java-8-functional-interfaces
-
最好在每个条目中使用
enum和execute()方法 -
也许你过于复杂了。为什么不为您的 4 个可能的命令设置一个 switch 语句或 if else 块。
-
禁止使用条件分支,如 if/else 或 switch。这就是为什么必须使用其他方法来解决这个问题