开发者

run programs with an argument?

开发者 https://www.devze.com 2023-02-28 23:25 出处:网络
How does one go about making programs that accept added arguments at command line? such as the program printMe.java

How does one go about making programs that accept added arguments at command line?

such as the program printMe.java

if i ran it like

java printMe im so cool

it would print, "im so cool"

Im looking to figure out how i can pass extra informatio开发者_JAVA技巧n to my program through command line arguments!


public static void main(String[] args) // note "args"

Java uses that String array to represent command-line arguments to the application.


All Java programs can take arguments.

Simple look at the String[] that gets passed in as the argument to your main method: it contains the command line arguments!


public class PrintMe {

    public static void main(String[] args){
        if(args.length > 0){
            System.out.println(args[0]);
        }
    }

}
$ javac PrintMe.java
$ java PrintMe "I'm so cool"
I'm so cool


By using the String[] args that is passed into the main function. This gets filled up with all of the specified parameters.

public static void main ( String[] args )


The Java main method has a parameter String[] args which will contain any command line arguments passed.

So, in your case, the PrintMe class's main method would look something like:

public static void main(String[] args) {
    for(String s : args) {
        System.out.print(s + " ");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消