Java 将命令行参数传递给方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1654074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:26:26  来源:igfitidea点击:

Java passing command line arguments to methods

javacommand-linearguments

提问by rize

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

我正在编写一个程序,它将两个单词作为命令行参数,对它们执行某些操作并打印出结果。我正在编写一个类来处理这个问题,我的问题是:在类中的方法之间传递作为命令行参数给出的两个单词的最佳方法是什么?为什么我不能在带有“args”的构造函数中使用通常的“this.variable =”?

回答by Jon Skeet

You can, if you pass argsto the constructor:

你可以,如果你传递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
    }
}

回答by Pascal Thivent

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 argsarray or its values to a constructor. Something like this:

如果您希望在命令行上传递一些参数,您可以使事情变得更加健壮并检查它们是否确实被传递了。然后,将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);
    }
}