我正在编写一个程序,它接受两个单词作为命令行参数,对它们进行某些操作,并打印出结果。我正在编写一个处理这个程序的类,我的问题是:在类的方法之间传递作为命令行参数给出的两个单词的最佳方式是什么?为什么我不能在构造函数中使用“this.variable =”和“args”?
我正在编写一个程序,它接受两个单词作为命令行参数,对它们进行某些操作,并打印出结果。我正在编写一个处理这个程序的类,我的问题是:在类的方法之间传递作为命令行参数给出的两个单词的最佳方式是什么?为什么我不能在构造函数中使用“this.variable =”和“args”?
args
传递给构造函数来实现: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
}
}
args
数组或其值传递给构造函数。类似于这样的代码: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);
}
}