Command Line Flags in Minitab
Here’s the translated code and explanation in Java, formatted for Hugo:
Our first program will demonstrate how to use command-line flags in Java. We’ll use the Apache Commons CLI library, which provides similar functionality to Go’s flag
package.
import org.apache.commons.cli.*;
public class CommandLineFlags {
public static void main(String[] args) {
// Define the options
Options options = new Options();
options.addOption("word", true, "a string");
options.addOption("numb", true, "an int");
options.addOption("fork", false, "a bool");
options.addOption("svar", true, "a string var");
// Create a parser
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
try {
// Parse the command line arguments
CommandLine cmd = parser.parse(options, args);
// Retrieve the values
String word = cmd.getOptionValue("word", "foo");
int numb = Integer.parseInt(cmd.getOptionValue("numb", "42"));
boolean fork = cmd.hasOption("fork");
String svar = cmd.getOptionValue("svar", "bar");
// Print the values
System.out.println("word: " + word);
System.out.println("numb: " + numb);
System.out.println("fork: " + fork);
System.out.println("svar: " + svar);
System.out.println("tail: " + String.join(" ", cmd.getArgs()));
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("CommandLineFlags", options);
System.exit(1);
}
}
}
To experiment with the command-line flags program, first compile it and then run the resulting class file directly.
$ javac -cp commons-cli-1.4.jar CommandLineFlags.java
Try out the compiled program by first giving it values for all flags.
$ java -cp .:commons-cli-1.4.jar CommandLineFlags -word opt -numb 7 -fork -svar flag
word: opt
numb: 7
fork: true
svar: flag
tail:
Note that if you omit flags they automatically take their default values.
$ java -cp .:commons-cli-1.4.jar CommandLineFlags -word opt
word: opt
numb: 42
fork: false
svar: bar
tail:
Trailing positional arguments can be provided after any flags.
$ java -cp .:commons-cli-1.4.jar CommandLineFlags -word opt a1 a2 a3
word: opt
...
tail: a1 a2 a3
The Apache Commons CLI library allows flags to appear anywhere in the command line, unlike Go’s flag package which requires all flags to appear before positional arguments.
Use -h
or --help
flags to get automatically generated help text for the command-line program.
$ java -cp .:commons-cli-1.4.jar CommandLineFlags -h
usage: CommandLineFlags
-fork a bool
-numb <arg> an int
-svar <arg> a string var
-word <arg> a string
If you provide a flag that wasn’t specified, the program will print an error message and show the help text again.
$ java -cp .:commons-cli-1.4.jar CommandLineFlags -wat
Unrecognized option: -wat
usage: CommandLineFlags
...