1

How do I pick the methods in my program to run using command line arguments? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.

1
  • Do you want to invoke programs within Java as like running them at command line at want to retrieve the output? Commented Aug 1, 2012 at 18:35

4 Answers 4

3

You can parse arguments with a function like this:

private void parseArguments(String[] args)
  {
    int i = 0;
    String curArg;

    while (i < args.length && args[i].startsWith("-"))
    {
      curArg = args[i++];

      if ("-S".compareTo(curArg) == 0)
      {
        if (i < args.length)
        {
            String image = args[i++];
            processImage()
        }
        else
        {
          // ERROR
        }
      }
    } 
  }

Your main method should always have String[] args which contains arguments split on the space character. There are also plenty of libraries you can use to parse command line arguments. This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).

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

1 Comment

@KimberleeGraham-Knight Then you should click the checkmark next to this answer.
3

http://commons.apache.org/cli/

This should help. and here's how to use it: http://commons.apache.org/cli/usage.html

3 Comments

This is a poor answer. While the library you link to may be helpful, it isn't clear in what way the user should expect to use it. Further, it is best practice on this site to provide more than 'just a link' for an answer.
Thanks for the link, If my understanding is correct, it just maps the Strings not method calls (or) invocations.
@thinksteep - correct, you then map the strings to the relevant method calls.
0

You may need to write different methods for each purpose and have if/else conditions based on command input.

Comments

0

why not read the arguments passed and read subsequent value to do the required stuff ie,

java yourprogram -a1 something -a2 somethingelse

and in your program

public static void main(String[] args){
 for(int i=0;i<args.length;i++){
  switch(args[i]){//you can use if-else to deal with string...
  case "-a1":read args[i+1] to get value to do somethng
  case "-a2": read args[i+1] to get value to do something else
 }
}

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.