我正在尝试从main方法参数列表创建一个Boat对象数组,然后使用.name将args数组中给出的名称赋值给boat。格式化这个的正确方法是什么?
public static void main(String[] args) {
for(int i = 0; i < args.length; i++){
Boat args[i] = new Boat();
args[i].name = args[i];
}
}
答案 0 :(得分:3)
Boat boat = new Boat();
boat.name = args[i];
// and then do something with the Boat, I guess...
答案 1 :(得分: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];
}
答案 2 :(得分: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
。
答案 3 :(得分:0)
首先,您需要创建船只阵列
Boat[] boats = new Boat[args.length];
然后,遍历args获取名称,并为每个名称创建一个名为的新船并将其保存在船只阵列的位置
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
}
答案 4 :(得分: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]);
}