0

我正在尝试从主方法参数列表中创建一个 Boat 对象数组,然后将 args 数组中给出的名称分配给带有 .name 的船。格式化它的正确方法是什么?

public static void main(String[] args) {
    for(int i = 0; i < args.length; i++){
        Boat args[i] = new Boat();
        args[i].name = args[i];
    }
}
4

5 回答 5

3
Boat boat = new Boat();
boat.name = args[i];
// and then do something with the Boat, I guess...
于 2013-10-22T23:54:39.347 回答
2

当你这样做

for(int i=0; i<args.length; i++) { Boat
    args[i] = new Boat();

您遇到了范围问题。您需要更改Boat数组的名称并在循环之外声明它(因此它只创建一次)。

Boat armada[args.length];
for(int i = 0; i < args.length; ++i) {
    armada[i] = new Boat();
    armada[i].name = args[i];
}
于 2013-10-22T23:56:30.513 回答
1
public static void main(String[] args) {
  Boat[] boats = new Boat[args.length];
  for (int i=0; i< args.length; i++) {
    boats[i] = new Boat();
    boats[i].name = args[i];
  }
}

我做了一个假设,您的Boat班级有一个public名为name.

于 2013-10-22T23:59:51.417 回答
0

首先,您需要创建船只阵列

Boat[] boats = new Boat[args.length];

然后,遍历 args 以获取名称,并为每个名称创建一个具有该名称的新船并将其保存在 boats 数组的位置

for(int i = 0; i < args.length; i++){
    Boat boat = new Boat(); //Create new boat
    boat.name = args[i]; //Give the name to the new boat
    boats[i] = boat; //And save it into the array
}
于 2013-10-23T00:02:18.100 回答
0

Add a new constructor which accepts name as argument and try the following


        Boat[] boat = new Boat[args.length]; 
            for (int iter = 0; iter < args.length; iter++) {
                boat[iter] = new Boat(args[iter]);
        }

于 2013-10-23T00:02:44.100 回答