Java将命令行参数传递给方法
问题描述:
我正在编写一个程序,它将两个单词作为命令行参数,对它们执行某些操作并打印出结果。我在写一个类来处理这个问题,我的问题是:在类中的方法之间传递两个作为命令行参数的单词的最佳方式是什么?为什么我不能在构造函数中用“args”使用通常的“this.variable =”?Java将命令行参数传递给方法
答
可以,如果你通过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);
}
}
+0
+1让用户知道命令行参数的用法。我还没有看到许多程序员正在这样做。尽管这篇文章很老,但我喜欢你处理CLA的方式。从你身上学到了一些东西。 :) – Saad 2017-03-28 00:01:00
谢谢!我是一个带有命令行参数的初学者。 – rize 2009-10-31 11:12:35
这太可爱了:) +1对于 – 2009-10-31 11:39:17
我得到了'方法run()未定义类型Program'。在不同版本的Java中可能会有所不同?我正在使用Java 5. – rize 2009-10-31 11:46:34