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
2009-10-31 11:08:10
Thank You! I'm a beginner with command line args.
rize
2009-10-31 11:12:35
it was too cute :) +1 for that
Rakesh Juyal
2009-10-31 11:39:17
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
2009-10-31 11:46:34
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
2009-10-31 11:52:47
Ok, now I understand the structure, many thanks!
rize
2009-10-31 12:28:50
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
2009-10-31 14:40:05