001package jargs.examples.gnu;
002
003import jargs.gnu.CmdLineParser;
004
005public class OptionTest {
006
007    private static void printUsage() {
008        System.err.println("usage: prog [{-v,--verbose}] [{-n,--name} a_name]"+
009                           "[{-s,--size} a_number] [{-f,--fraction} a_float]");
010    }
011
012    public static void main( String[] args ) {
013        CmdLineParser parser = new CmdLineParser();
014        CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
015        CmdLineParser.Option size = parser.addIntegerOption('s', "size");
016        CmdLineParser.Option name = parser.addStringOption('n', "name");
017        CmdLineParser.Option fraction = parser.addDoubleOption('f', "fraction");
018
019        try {
020            parser.parse(args);
021        }
022        catch ( CmdLineParser.OptionException e ) {
023            System.err.println(e.getMessage());
024            printUsage();
025            System.exit(2);
026        }
027
028        // Extract the values entered for the various options -- if the
029        // options were not specified, the corresponding values will be
030        // null.
031        Boolean verboseValue = (Boolean)parser.getOptionValue(verbose);
032        Integer sizeValue = (Integer)parser.getOptionValue(size);
033        String nameValue = (String)parser.getOptionValue(name);
034        Double fractionValue = (Double)parser.getOptionValue(fraction);
035
036        // For testing purposes, we just print out the option values
037        System.out.println("verbose: " + verboseValue);
038        System.out.println("size: " + sizeValue);
039        System.out.println("name: " + nameValue);
040        System.out.println("fraction: " + fractionValue);
041
042        // Extract the trailing command-line arguments ('a_number') in the
043        // usage string above.
044        String[] otherArgs = parser.getRemainingArgs();
045        System.out.println("remaining args: ");
046        for ( int i = 0; i < otherArgs.length; ++i ) {
047            System.out.println(otherArgs[i]);
048        }
049
050        // In a real program, one would pass the option values and other
051        // arguments to a function that does something more useful.
052
053        System.exit(0);
054    }
055
056}