Handling command-line arguments in the controller

You can add code to your controller class to handle POSIX-style command line arguments, just like the main FrontEnd class for CT does.

This is done through a library called GetOpt, for which there is a good general tutorial available.

To use the Java implementation of GetOpt in your controller, include the following imports:

import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;

The following is an example of part of a main method in a controller that uses GetOpt.

It has three possible command-line options

  • -h or --help
  • -n or --numRounds num
  • -f or --fixedReward num
        public static void main(String[] args)
        {
    
            LongOpt[] longopts = new LongOpt[3];
            longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
            longopts[1] = new LongOpt("fixedReward", LongOpt.REQUIRED_ARGUMENT, null, 'f');
            longopts[2] = new LongOpt("numRounds", LongOpt.OPTIONAL_ARGUMENT, null,'n');
            Getopt go = new Getopt("coloredtrails", args, "f:n:", longopts);
            go.setOpterr(true);
            int c;
            String arg;
    
            boolean useFixedReward = false;
            int fixedReward = 0;
    
            try {
                while ((c = go.getopt()) != -1) {
                    switch (c) {
                        case 'h':
                            printUsage();
                            break;
                        case 'f':
                            useFixedReward = true;
                            fixedReward = Integer.parseInt(go.getOptarg());
                            break;
                        case 'n':
                            numRounds = Integer.parseInt(go.getOptarg());
                            break;
                        default:
                            System.out.println("Unknown option:" + c);
                            printUsage();
                            System.exit(1);
                            break;
                    }
                }
            } catch (Exception e) {
                printUsage();
                System.err.println("Error: Bad Input.");
                System.exit(1);
            }