devxlogo

Simplify Command-Line Argument Parsing

Simplify Command-Line Argument Parsing

ArgumentParser simplifies command-line argument processing by separating arguments into positional parameters and options (any argument starting with “-” or “/” is considered an option, which may specify a value). Construct an ArgumentParser instance with your command-line arguments, then ask the ArgumentParser for parameters and options:

 java YourClass -level=5 firstParam -verbose secondParamin YourClass.java:    public static void main(String[] args) {        ArgumentParser p = new ArgumentParser(args);        if (p.hasOption("?") {            printUsage();        }        else {            boolean verboseMode = p.hasOption("verbose");            level = p.getOption("level");            doSomethingWithParams(p.nextParam(), p.nextParam());        }    }==================== ArgumentParser.java ====================import java.util.*;public class ArgumentParser {    public ArgumentParser(String[] args) {        for (int i = 0; i < args.length; i++) {            if (args[i].startsWith("-") || args[i].startsWith("/")) {                int loc = args[i].indexOf("=");                String key = (loc > 0) ? args[i].substring(1, loc) :args[i].substring(1);                String value = (loc > 0) ? args[i].substring(loc+1) :"";                options.put(key.toLowerCase(), value);            }            else {                params.addElement(args[i]);            }        }    }    public boolean hasOption(String opt) {        return options.containsKey(opt.toLowerCase());    }    public String getOption(String opt) {        return (String) options.get(opt.toLowerCase());    }    public String nextParam() {        if (paramIndex < params.size()) {            return (String) params.elementAt(paramIndex++);        }        return null;    }    private Vector params = new Vector();    private Hashtable options = new Hashtable();    private int paramIndex = 0;}
See also  The Importance of Data Security in Hospitality
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist