views:

1923

answers:

7

I am trying to detect whether the 'a' was entered as the first string argument.

+1  A: 

Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).

Joachim Sauer
+4  A: 
public class YourClass {
    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("a"))
            ...
Björn
+4  A: 

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}
Rob
A: 

Command line arguments are accessible via String[] args parameter of main method.

For first argument you can check args[0]

entire code would look like

public static void main(String[] args) {
    if ("a".equals(args[0])) {
         // do something
    }
}
Darth
+6  A: 

Every Java program starts with

public static void main(String[] args) {

That array of String that main takes as a parameter holds the command line arguments to your program. If the user runs your program as

$ java myProgram a

then args[0] will hold the String "a".

Bill the Lizard
A: 

As everyone else has said... the .equals method is what you need.

In the off chance you used something like:

if(argv[0] == "a")

then it does not work because == compares the location of the two objects (physical equality) rather than the contents (logical equality).

Since "a" from the command line and "a" in the source for your program are allocated in two different places the == cannot be used. You have to use the equals method which will check to see that both strings have the same characters.

Another note... "a" == "a" will work in many cases, because Strings are special in Java, but 99.99999999999999% of the time you want to use .equals.

TofuBeer
+6  A: 

Use the apache commons cli if you plan on extending that past a single arg.

"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."

Commons CLI supports different types of options:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)
John Ellinwood