public static void main(String[] args) throws Exception { JSAP jsap = new JSAP(); // create a flagged option we'll access using the id "count". // it's going to be an integer, with a default value of 1. // it's required (which has no effect since there's a default value) // its short flag is "n", so a command line containing "-n 5" // will print our message five times. // it has no long flag. FlaggedOption opt1 = new FlaggedOption("count") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(true) .setShortFlag('n') .setLongFlag(JSAP.NO_LONGFLAG); jsap.registerParameter(opt1); JSAPResult config = jsap.parse(args); for (int i = 0; i < config.getInt("count"); ++i) { System.out.println("Hello, World!"); } }
That's pretty verbose. Later on you'll see ways to trim this down quite a bit. Here's what's going on:
We create a new JSAP
to do the parsing.
We create a new FlaggedOption
so we can
tell the program how many times to print the message.
It has an ID of "count", which is only used internally by our program to retrieve the value.
It's using an IntegerStringParser
to convert the value to an Integer
, and
it has a default value of 1.
It's required, but since we're specifying a default value, the requirement will always be met.
It has a short flag "n", so the syntax is "-n 5" to print the message five times, for example.
It has no long flag.
We register the flagged option with the parser we created in the beginning.
We tell the parser to parse the command line arguments, and store the result in a variable called "config".
We print the message.
The output of the program looks like this:
[mlamb@morbo]$
java com.martiansoftware.jsap.examples.Manual_HelloWorld_2Hello, World!
[mlamb@morbo]$
java com.martiansoftware.jsap.examples.Manual_HelloWorld_2 -n 5Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!
So far, so good. Let's add a switch.