Skip to content
Advertisement

command line argument with variable name in java in specific format

I am trying to get a CLI for my class in the format of

java demo --age 20 --name Amr --school Academy_of_technology --course CS

how do I achieve this.

I saw one of the solutions and tried that over here Command Line Arguments with variable name


Map<String, String> argsMap = new LinkedHashMap<>();
    for (String arg: args) {
        String[] parts = arg.split("=");
        argsMap.put(parts[0], parts[1]);
    }

    argsMap.entrySet().forEach(arg-> {
        System.out.println(arg.getKey().replace("--", "") + "=" + arg.getValue());
    });


but the above code’s input format was like javac demo --age=20 --name=Amar school=AOT course=CS

and i want my i/p format to be like this java demo --age 20 --name Amr --school Academy_of_technology --course CS

so i replaced the “=” with ” ” and i got array out of bounds as epected. I was thinking if regex would be the way.

The code always expects 4 input.

Advertisement

Answer

The below code will work if key and value pairs are only space-separated.

public static void main(String[] args) {

    Map<String, String> argMap = new LinkedHashMap<>();

    for(int ind=0; ind<args.length; ind+=2) {
        argMap.put(args[ind], args[ind+1]);
    }

    for(Map.Entry<String, String> entrySet: argMap.entrySet()) {
        String property = entrySet.getKey().substring(2);
        String value = entrySet.getValue();
        System.out.println("key = " + property + ", value = " + value);
    }

}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement