2

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.

Abal
  • 113
  • 11
  • 1
    In your first CLI example, you are using both syntax one that separates key and values by space and another that separates using `=`. I suspect that's a typo. Or you really want to work in both ways? – Omkar76 Sep 28 '20 at 06:20
  • the code i reffered too had the input format using ```=``` and i want spaces instead of that like ```java demo --age 20 --name Amar ``` – Abal Sep 28 '20 at 06:26
  • You won't be able to do the split("="). Each argument will be a token in 'args'. – matt Sep 28 '20 at 06:27
  • 3
    Have you considered using a library? https://argparse4j.github.io/ – matt Sep 28 '20 at 06:28

1 Answers1

1

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);
    }

}
  • @matt edited as per your comment. My intention was to have a check if user keys in a property without a corresponding value, which will cause ArrayIndexOutOfBoundsException. I leave that to Abal. – Aravind Sharma Sep 28 '20 at 07:00
  • 1
    That makes sense, but you used the same condition both for the loop and your check. I think you would want the second condition to compare 'ind+1' to the length. – matt Sep 28 '20 at 07:04