简体   繁体   中英

Java passing command line arguments to methods

I'm writing a program, which takes two words as command line arguments, does something to them, and prints out the result. I'm writing a class to handle this, and my question is: what is the best way to pass two words given as command line arguments between methods in a class? Why can't I use the usual "this.variable = " in the constructor with "args"?

You can, if you pass args to the constructor:

public class Program
{
    private String foo;
    private String bar;

    public static void main(String[] args) 
    {
        Program program = new Program(args);
        program.run();
    }

    private Program(String[] args)
    {
        this.foo = args[0];
        this.bar = args[1];
        // etc
    }

    private void run()
    {
        // whatever
    }
}

If you expect some arguments to be passed on the command line, you can make things a little more robust and check that they are indeed passed. Then, pass the args array or its values to a constructor. Something like this:

public class App {
    private final String arg0;
    private final String arg1;

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("arguments must be supplied");
            System.out.println("Usage: java App <arg0> <arg1>");
            System.exit(1);
        }
        // optionally, check that there are exactly 2 arguments
        if (args.length > 2) {
            System.out.println("too many arguments");
            System.out.println("Usage: java App <arg0> <arg1>");
            System.exit(1);
        }

        new App(args[0], args[1]).echo();
    }

    public App(String arg0, String arg1) {
        this.arg0 = arg0;
        this.arg1 = arg1;
    }

    public void echo() {
        System.out.println(arg0);
        System.out.println(arg1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM