传递类的参数

时间:2014-01-08 16:55:29

标签: java

如何从main方法将这些参数传递给类HelloClass,其中包含以下参数:

HelloClass 4d.txt 1000 9 0.6 [这是来自命令行]

HelloClass是一个类名 4d.txt是文件名 1000是int参数值 9是int参数值 0.6是浮点参数值

应该在表格

中调用它

类主要方法是

public static void main(String[] args) {
    HelloClass start = new HelloClass(args);

}

并且args数组现在应该是{4d.txt,1000,9,0.6},我怎么能一次将这个args传递给类HelloClass构造函数,而不是从命令行控制台传递

1 个答案:

答案 0 :(得分:1)

怎么样:

public class HelloClass {

    /**
     * be sure to handle errors and exceptions
     *
     */
    public HelloClass(String[] params) {
        if (params.length == 4) {
            String paramOne = params[0];
            int paramTwo = Integer.parseInt(params[1]);
            int paramThree = Integer.parseInt(params[2]);
            float paramFour = Float.parseFloat(params[3]);

           //Now do something with those parameters;
        }
    }
}

现在在主要内容中调用它:

public static void main(String[] args) {
    //If you are getting your arguments from Command line
    HelloClass myHelloClassWithCommandArguments = new HelloClass(args);

    //If you are passing pre-defined arguments or such.
    HelloClass myHelloClassWithCustomArguments = new HelloClass(new String[]{"d4.txt", "1000", "9", "0.6"});
}