Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I parse command line style input?

Tags:

java

text

parsing

I'm writing a program where a user can input something like

add 5 2

or

define foo

Right now the only way I know to handle this input is a bunch of if/else if statements, ie

if(args[0] == "add") add();
else if (args[0] == "define") define();
else print("Command not found.");

Is there a better way to do this, or maybe some sort of data structure/algorithm that's standard for these types of inputs? I'm using Java specifically, but I'd prefer a language-agnostic answer if possible. Thanks!

like image 450
ahota Avatar asked Jan 27 '26 13:01

ahota


2 Answers

Design pattern Command can be used for this goals. For example:

abstract class Command {
    abstract public String getCommandName();
    abstract public String doAction();
}

To define you own function just implement Command class:

class AddCommand extends Command {
    @Override
    public String getCommandName() {
        return "add";
    }

    @Override
    public String doAction() {
        // do your action
    }
}

then your main class should looks like:

public class Main {

    private static Map<String, Command> commands = new HashMap<String, Command>();

    private static void init() {
        Command addCommand = new AddCommand();
        commands.put(addCommand.getCommandName(), addCommand);
    }

    public static void main (String[] args) {
        init();
        if (args[0] != null) {
            Command command = commands.get(args[0]);
            if (command != null) {
                System.out.println(command.doAction());
            } else {
                System.out.println("Command not found");
            }
        }
    }
like image 153
Patison Avatar answered Jan 29 '26 01:01

Patison


You could use a switch statement:

switch (args[0]) {
    case "add":
        // do your adding stuff
        break;
    case "define":
        // do your defining stuff
        break;
    default:
        // command not found
}

switch is a common feature in most languages (some languages use different syntax, for example Ruby uses case/when instead of switch/case). It only works on Strings starting from Java 1.7 though.

Also, some languages have Dictionarys and functions in variables, so for example in Ruby you could do this:

myDictionary = { "add" => someFunctionToAddStuff,
                 "define" => anotherFunction }
myDictionary["define"] # returns anotherFunction
like image 23
tckmn Avatar answered Jan 29 '26 02:01

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!