【发布时间】:2015-10-08 16:03:16
【问题描述】:
希望标题是解释性的。
1 public void commander(){
2 Scanner input = new Scanner(System.in);
3 System.out.println("\nWelcome to my application."
4 + "\nType the command you want to use,"
5 + "or type 'exit' to close the program.");
6 while (input.next() != "exit") {
7 List<String> userInput = Arrays.asList(input.next().split(" "));
8 Class<? extends RunnableCommand> command = Commands.commandsMap().get(userInput.get(0));
9 userInput.remove(0);
10 // command.run(userInput); ?!
11 }
第 8 行: RunnableCommand 是一个提供 run() 方法的接口,由表示命令的每个类实现(受策略模式的启发)。
第 10 行:这就是问题所在。每个“命令类”的 run() 方法可以有 1、2 或 3 个字符串作为输入。
有没有办法将 userInput 的每个元素作为 run() 方法的输入?
【问题讨论】:
-
input.next() != "exit"-> How do I compare strings in Java? -
另外
next只能返回一个令牌,所以next().split(" ")没有意义。你可能对nextLine感兴趣。 -
input.next() != "exit"不会按照您(可能)期望的方式工作。试试!"exit".equals(input.next())。 -
谢谢大家,这些都是我完全需要知道的。
-
为什么不修改
run()方法来接受一个List?正如@Pshemo 和@f_puras 所指出的那样,那种春天可能不是你想要的。看看这个问题 - stackoverflow.com/questions/767372/java-string-equals-versus
标签: java string list methods input