Java Command line arguments

2019-01-03 07:11发布

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

9条回答
够拽才男人
2楼-- · 2019-01-03 07:39

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!?
    }
}
查看更多
Animai°情兽
3楼-- · 2019-01-03 07:40
public class YourClass {
    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("a")){
            //...
        }
    }
}
查看更多
Explosion°爆炸
4楼-- · 2019-01-03 07:41

Every Java program starts with

public static void main(String[] args) {

That array of type 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".

查看更多
登录 后发表回答