【问题标题】:Java: turn List<String> into input for method(String, String, String)Java:将 List<String> 转换为方法的输入(字符串,字符串,字符串)
【发布时间】: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


【解决方案1】:

像这样实现run方法:

public void run(String... commands) {
  ...
}

您可以通过传递数组或逗号分隔的参数来调用它。

command.run(input1);
command.run(input1, input2);
command.run(input1, input2, input3);

command.run(userInput.toArray(new String[0]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多