HelloWorld_3
Prev | Chapter 3. Quick Start | Next

## HelloWorld_3

        public static void main(String[] args) throws Exception {
            JSAP jsap = new JSAP();

            FlaggedOption opt1 = new FlaggedOption("count")
                                    .setStringParser(JSAP.INTEGER_PARSER)
                                    .setDefault("1")
                                    .setRequired(true)
                                    .setShortFlag('n')
                                    .setLongFlag(JSAP.NO_LONGFLAG);

            jsap.registerParameter(opt1);

            // create a switch we'll access using the id "verbose".
            // it has the short flag "-v" and the long flag "--verbose"
            // this will govern whether we say "Hi" or "Hello".
            Switch sw1 = new Switch("verbose")
                            .setShortFlag('v')
                            .setLongFlag("verbose");

            jsap.registerParameter(sw1);

            JSAPResult config = jsap.parse(args);

            for (int i = 0; i < config.getInt("count"); ++i) {
                System.out.println((config.getBoolean("verbose") ? "Hello" : "Hi")
                                    + ", World!");
            }

        }

What did we do? We created a new `Switch` to determine how verbose we're going to be with our greeting, registered it with `JSAP`, and read its value inside the print loop. That might still seem like a lot of code for this little feature, but let's look at all the ways we can invoke the program now:

    [mlamb@morbo]$ java com.martiansoftware.jsap.examples.Manual_HelloWorld_3 -n 2
    Hi, World!
    Hi, World!

    [mlamb@morbo]$ java com.martiansoftware.jsap.examples.Manual_HelloWorld_3 -n 3 -v
    Hello, World!
    Hello, World!
    Hello, World!

    [mlamb@morbo]$ java com.martiansoftware.jsap.examples.Manual_HelloWorld_3 --verbose
    Hello, World!

    [mlamb@morbo]$ java com.martiansoftware.jsap.examples.Manual_HelloWorld_3 -vn 2
    Hello, World!
    Hello, World!

That last one is the most interesting - note that we were able to combine multiple short flags ("v" and "n"). `JSAP` allows this for as many short flags as you want - provided that at most one of them is an `Option` (as opposed to a `Switch`) and it's the last one in the list.

For the next example, we'll use an unflagged option to specify to whom we really want to say hello. It will be optional, defaulting to "World" for backwards compatibility with our earlier examples. :) We'll also make it greedy, so it consumes the rest of the command line to allow multiple values.

Prev | Up | Next
HelloWorld_2 | Home | HelloWorld_4