English 中文(简体)
First Application
  • 时间:2024-09-17

Apache Commons CLI - First Apppcation


Previous Page Next Page  

Let s create a sample console based apppcation, whose purpose is to get either sum of passed numbers or multippcation of passed numbers based on the options used.

Create a java class named CLITester.

Example

CLITester.java


import org.apache.commons.cp.CommandLine;
import org.apache.commons.cp.CommandLineParser;
import org.apache.commons.cp.DefaultParser;
import org.apache.commons.cp.Options;
import org.apache.commons.cp.ParseException;
pubpc class CLITester {
   pubpc static void main(String[] args) throws ParseException {
      //***Definition Stage***
      // create Options object
      Options options = new Options();
      
      // add option "-a"
      options.addOption("a", false, "add numbers");
      
      // add option "-m"
      options.addOption("m", false, "multiply numbers");

      //***Parsing Stage***
      //Create a parser
      CommandLineParser parser = new DefaultParser();

      //parse the options passed as command pne arguments
      CommandLine cmd = parser.parse( options, args);

      //***Interrogation Stage***
      //hasOptions checks if option is present or not
      if(cmd.hasOption("a")) {
         System.out.println("Sum of the numbers: " + getSum(args));
      } else if(cmd.hasOption("m")) {
         System.out.println("Multippcation of the numbers: " + getMultippcation(args));
      }
   }
   pubpc static int getSum(String[] args) {
      int sum = 0;
      for(int i = 1; i < args.length ; i++) {
         sum += Integer.parseInt(args[i]);
      }
      return sum;
   }
   pubpc static int getMultippcation(String[] args) {
      int multippcation = 1;
      for(int i = 1; i < args.length ; i++) {
         multippcation *= Integer.parseInt(args[i]);
      }
      return multippcation;
   }
}

Output

Run the file, while passing -a as option and numbers to get the sum of the numbers as result.


java CLITester -a 1 2 3 4 5
Sum of the numbers: 15

Run the file, while passing -m as option and numbers to get the multippcation of the numbers as result.


java CLITester -m 1 2 3 4 5
Multippcation of the numbers: 120
Advertisements