Sunday, September 25, 2011

Reading Command Line Arguments in Java

In console applications, arguments sometimes play an important role. They may be used to set the program's behavior according to external (as in external to the program) variables. These external variables can be sent to the program as strings which the program interprets as a String vector.
public class CmdLineProgram 
{
    /*
     * Precondition:
     * The program knows the minimum and maximum number of arguments
     * which he allows 
     */
    public static void main(String[] args)
    {
        int minNrOfArgs = 0;    //Minimum number of arguments
        int maxNrOfArgs = 2;    //Maximum number of arguments
        try
        {
            if(args.length >= minNrOfArgs && args.length <=maxNrOfArgs)
            {
                if(args.length!=0)
                {
                    System.out.println("The arguments are: ");
                    for(String s: args)
                        System.out.println(s);
                }
                System.out.println("Total number of arguments: " 
                                  + args.length);
            }
            else
            {
                if(args.length <= minNrOfArgs)
                    throw new Exception("Number of arguments is "
                                        + args.length
                                        + ".\n" 
                                        + "At least "
                                        + minNrOfArgs
                                        + " are required.");
                else
                    throw new Exception("Number of arguments is "
                                        + args.length
                                        + ".\n" 
                                        +"At most "
                                        + minNrOfArgs
                                        + " are permitted.");
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }
}
What the program does:
Knowing the minimum and maximum number of arguments, the program checks if the length of the argument String vector (args) is between those values. If that is true, it will output the number of arguments and the value of each argument using a foreach loop (still, he will not output the arguments if he didn't receive any and will only show 0).
If the number of arguments is not correct (too many of too few) it will throw an exception and output that exception.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger