接受命令提示参数和构造对象

时间:2014-10-15 06:15:48

标签: java

我需要接受命令提示符参数,并使用它们来构造一个对象。 我带了很多人和船的大小。

  

public RiverCrossingPuzzle(int numEach,int boatSize)

     

使用numEach数量的食人族创建一个RiverCrossingPuzzle   numEach有一艘船可以携带的传教士数量   boatSize传教士/食人族的数量。例如,输入可以是   " -n"," 4"," -b"," 3"

我应该这样做:

this.numEach = Integer.parseInt(args[2]);
this.boatSize = Integer.parseInt(args[4]);

或者像这样:

int numEach = Integer.parseInt(args[2]);
int boatSize = Integer.parseInt(args[4]);
this.boatSize = boatSize;
this.numEach = numEach;

3 个答案:

答案 0 :(得分:2)

在调用构造函数之前,我会读取并解析命令行参数。

public static void main (String[] args)
{
    int numEach = 0; // or some other default value that makes sense
    int boatSize = 0; // or some other default value that makes sense
    if (args.length > 1)
        numEach = Integer.parseInt(args[1]);
    if (args.length > 3)
        boatSize = Integer.parseInt(args[3]);
    RiverCrossingPuzzle puzzle = new RiverCrossingPuzzle (numEach, boatSize);
}

如果无法在int处解析命令行参数,还应添加异常处理。

顺便说一句,根据您的"-n", "4", "-b", "3"示例,您应该阅读args[1]args[3]

答案 1 :(得分:0)

我会按照try解析命令行方法,因为它也处理无效输入:

public static void main (String[] args){

    RiverCrossingPuzzle puzzle;
    try{
        int numEach= Integer.parseInt(args[1]);
        int boatSize= Integer.parseInt(args[3]);
        puzzle = new RiverCrossingPuzzle (numEach, boatSize);
    }catch(NumberFormatException e){
        e.printStackTrace(); // maybe log it?
        System.out.println("Invalid command line arguments passed in!! You should pass arguments such as : -n NUMBER -b NUMBER");
        return; 
   }
}

答案 2 :(得分:0)

您可能想要查看的内容也是您的程序参数。您期望用户使用-n 4 -b 3的参数启动程序,但情况并非总是如此。用户可以使用-n-b反向启动该程序。你总是要假设用户会试图打破你的应用程序(即使这可能只是一个练习,这是一个很好的习惯)。现在你怎么解决这个问题?最简单的方法是查看指标-n-b在程序参数中的位置,如下所示:

public static void main(String[] args) {
    int nIndex = -1; //Just some value that clearly will never resolve in an array, suggesting it has not been found
    int bIndex = -1;
    for(int i = 0; i < args.length; i++)
        if (args[i].equals("-n"))
            nIndex = i + 1; //The next index will correspond to the value of -n
        else if (args[i].equals("-b"))
            bIndex = i + 1; //The next index will correspond to the value of -b
    int boatSize, numEach;
    if(nIndex != -1 && bIndex != -1 && nIndex < args.length && bIndex < args.length) {
        /*Check that they were both parsed AND that neither of them are outside of the array range
         *(such as starting with "-n 5 -b" and no value for b
         */
        boatSize = Integer.parse(args[bIndex]);
        numEach = Integer.parse(args[nIndex]);
    }

}