Skip to content

Instantly share code, notes, and snippets.

@kalaspuffar
Created November 21, 2022 22:12
Show Gist options
  • Save kalaspuffar/7b1a76aa41694fe472a3c266afc39d19 to your computer and use it in GitHub Desktop.
Save kalaspuffar/7b1a76aa41694fe472a3c266afc39d19 to your computer and use it in GitHub Desktop.
Small example on how to use apache commons.
import org.apache.commons.cli.*;
import java.io.PrintWriter;
public class CLI {
private static final Option ARG_ADD = new Option("a", "addition", false, "Add two numbers together");
private static final Option ARG_SUB = new Option("s", "subtraction", false, "Subtract two numbers");
private static final Option ARG_MUL = new Option("m", "multiplication", false, "Multiply two numbers");
private static final Option ARG_DIV = new Option("d", "division", false, "Divided two numbers");
private static final Option ARG_MINUS = new Option(null, "minus", true, "After result do a minus operation");
private static void printHelp(Options options) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(System.out);
pw.println("MathAPP " + Math.class.getPackage().getSpecificationVersion());
pw.println();
formatter.printUsage(pw, 100, "java -jar MathAPP.jar [options] number1 number2");
formatter.printOptions(pw, 100, options, 2, 5);
pw.close();
}
public static void main(String[] args) {
CommandLineParser clp = new DefaultParser();
Options options = new Options();
options.addOption(ARG_ADD);
options.addOption(ARG_SUB);
options.addOption(ARG_MUL);
options.addOption(ARG_DIV);
options.addOption(ARG_MINUS);
try {
CommandLine cl = clp.parse(options, args);
if (cl.getArgList().size() < 2) {
printHelp(options);
System.exit(-1);
}
int a = 0;
int b = 0;
try {
a = Integer.parseInt(cl.getArgList().get(0));
b = Integer.parseInt(cl.getArgList().get(1));
} catch (Exception e) {
printHelp(options);
e.printStackTrace();
System.exit(-1);
}
if(cl.hasOption(ARG_ADD.getLongOpt())) {
System.out.println(a + b);
} else if(cl.hasOption(ARG_SUB.getLongOpt())) {
System.out.println(a - b);
} else if(cl.hasOption(ARG_MUL.getLongOpt())) {
System.out.println(a * b);
} else if(cl.hasOption(ARG_DIV.getLongOpt())) {
System.out.println(a / b);
} else {
printHelp(options);
}
if(cl.hasOption(ARG_MINUS.getLongOpt())) {
String val = cl.getOptionValue(ARG_MINUS.getLongOpt());
int sum = a - (Integer.parseInt(val));
System.out.println(sum);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment