1

Hope the title is explanatory.

 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  }

Line 8: RunnableCommand is an interface that provides the run() method, implemented by every Class that represents a command (inspired by policy pattern).

Line 10: Here's the problem. The run() method of every "command class" can have 1, 2 or 3 String(s) as input.

Is there a way to give every element of userInput as input for the run() method?

d33pcode
  • 27
  • 7
  • 2
    `input.next() != "exit"` -> [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo Jul 19 '15 at 12:27
  • Also `next` can return only one token so `next().split(" ")` has no sense. You may be interested in `nextLine`. – Pshemo Jul 19 '15 at 12:29
  • `input.next() != "exit"` is not going to work the way you (probably) expect it to. Try `!"exit".equals(input.next())`. – f_puras Jul 19 '15 at 12:29
  • Thank you all, these were all things that I totally needed to know. – d33pcode Jul 19 '15 at 12:32
  • What is signature of `run` method (what arguments it expect)? Is it `run(String arg1, String arg2, String arg3)` or `run(String[] arguments)` or `run(String... arguments)` or maybe even instead of String you are using `Object`? – Pshemo Jul 19 '15 at 12:33
  • 1
    Why not modify the `run()` method to accept a List? And as @Pshemo and @f_puras have pointed out, that sort of spring isn't probably what you want. Take a look at this question - http://stackoverflow.com/questions/767372/java-string-equals-versus – Harshil Sharma Jul 19 '15 at 12:52

1 Answers1

2

Implement run method like this:

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

You can call it by passing an array or comma separate parameters.

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

or

command.run(userInput.toArray(new String[0]);
Wand Maker
  • 18,476
  • 8
  • 53
  • 87