我正在尝试从主方法参数列表中创建一个 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];
}
}
我正在尝试从主方法参数列表中创建一个 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];
}
}
Boat boat = new Boat();
boat.name = args[i];
// and then do something with the Boat, I guess...
当你这样做
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];
}
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
.
首先,您需要创建船只阵列
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
}
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]);
}