views:

753

answers:

2

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"?

+2  A: 

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
    }
}
Jon Skeet
Thank You! I'm a beginner with command line args.
rize
it was too cute :) +1 for that
Rakesh Juyal
I get 'the method run() is undefined for the type Program'. Might this be different in different versions of Java? I'm using Java 5.
rize
No, I just didn't include the run method - it wasn't meant to be a full program. The main point was passing args into the constructor. Will try to edit to add a run method though. (Am on phone, so tricky.)
Jon Skeet
Ok, now I understand the structure, many thanks!
rize
A: 

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);
    }
}
Pascal Thivent