2

If I have a String that contains a command and I want the program to read it and preform what it says.

example:

If I have a function:

private void move(float position, float speed){
.....
}

and a String

String command = "MOVE 305 5"

where the "MOVE" calls the move() function and “305“ is the position and the “5“ is the speed.

So, it should be like this:

move(305, 5);

How can I call the function using this String?

7
  • If all of your strings will be following the format of COMMAND arg1 arg2 argN then why not use String#Split? Commented Feb 2, 2017 at 10:14
  • You should learn about "reflection" in Java. With reflection you can use a string as input to invoke an existing method. Commented Feb 2, 2017 at 10:18
  • 1
    @IQV No reflection needed here. From experience, it should be avoided if possible. Commented Feb 2, 2017 at 10:22
  • @IQV true, but for something like this it's not a very optimal solution. This just requires some simple parsing. Commented Feb 2, 2017 at 10:22
  • user3879781 provided the move-command as an example. According to his profile he's interested in game-developing. So I think "move" will not be the only command, so it's necessary to use a broad approach. Commented Feb 2, 2017 at 10:25

2 Answers 2

5

If all of your commands are in the same format, you should have a switch statement, that will switch between the possible commands you may have. This way, you will call each function when it is needed with the args from the string.

Example:

String[] parts = command.split(' ');
switch(parts[0])
{
    case "MOVE":
        float position = Float.parseFloat(parts[1])
        float speed = Float.parseFloat(parts[2])
        move(position, speed);
        break;

    case ... :

    ...

    default:
        System.out.println("Unknown command");
        break;

}
Sign up to request clarification or add additional context in comments.

Comments

3

You may use an Enumeration for the different possible commands, along with a switch-case as already shown in other answers .

The enumeration :

 public enum CommandType{

        MOVE, STOP;
 }

And a sample usage :

String[] splitted = command.split("\\s");

CommandType currentCommand = CommandType.valueOf(splitted[0]);


switch(currentCommand){

    case MOVE : 
        move(Float.parseFloat(splitted[1]),Float.parseFloat(splitted[2]));
        break;
    case STOP : 
        stop();
        break;
    default :
        break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.