CS151 -- Lab 4

Command Line Arguments

In this lab we will be working with "command line arguments" to Java programs. By "command line arguments", I mean things that appear on the command line after "java Xxx". For example suppose you have a class names CLA:
        javac CLA.java
        java CLA a s this 1
    
the command line arguments would be "a s this 1"

Step 1

Actually create a class called CLA (acronym for Command Line Arguments). This class should only have a main method. Recall that the "signature" of a main method looks like
        public static void main(String[] args)
    
the "args" variable is there to hold the command line arguments.

Inside you main method write a loop to print all of the command line arguments (values and indices). For instance, in the example above, your program might should output

        0 a 
        1 s 
        2 this 
        3 1
    
Make sure the output of your program agrees with this sample. Also try your program with other command line arguments. (Note, to get command line arguments you will need to compile and run your java program from the command line, you cannot use the handy "run" button in VSC.)

Default Arguments

Frequently, during development, you want to use the same set of arguments every time; and do not want to bothered with entering them. This is especially true within VSC. If you use the "run" command it is difficult to set command line arguments. (It is possible, but I really do not recommend doing so.) What you can do fairly easily is to create a set of default arguments within your code.

The idea is to create an array of strings that the program will use if there are no command line arguments. That array would look exactly like the command line args. For instance (keeping with the example above),

        String[] myDefaults = {"a", "s", "this", "1"};
    
Then use this array of default arguments when the program starts with no arguments from the command line. For example, by adding the following code neat the top of your main method
        if (args.length = 0) {
            args = myDefaults;
        }
    

Extend the main method of CLA to have a set of default arguments and use them when no command line arguments are provided.

Future assignments will use command line arguments. The technique implemented in this lab should make your debugging and development easier.

Using command line arguments

Take your CLA program and adapt it so that it accepts two arguments from the command line. It should try to convert those two arguments to integers. If both parameters can be converted to integers, simply print the sum of the two integers. Otherwise print a message indicating which parameter is not an integer. (Hint, the easiest way to do this is to use Java's exception handling.)

On Completion

Send your CLA class to gtowell@brynmawr.edu.