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.

4
  • 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? Commented Sep 28, 2020 at 6: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 Commented Sep 28, 2020 at 6:26
  • You won't be able to do the split("="). Each argument will be a token in 'args'. Commented Sep 28, 2020 at 6:27
  • 3
    Have you considered using a library? argparse4j.github.io Commented Sep 28, 2020 at 6:28

1 Answer 1

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

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

2 Comments

@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.
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.

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.