【发布时间】:2020-08-25 08:33:14
【问题描述】:
我需要计算 mA_per_board,获取总电流,然后将此值分配给不同的板组合,以供将来比较和选择。问题是当我想为数组分配新的计算值时,只有最后一个值被分配。
这是我的构造函数:
class boards_and_current{
public String boards;
public int current;
public boards_and_current(String boards, int current){
this.boards = boards;
this.current = current;
}
public static ArrayList<boards_and_current> list_of_boards = new ArrayList();
public void addBoards(){
list_of_boards.add(new boards_and_current("2 boards", 0));
list_of_boards.add(new boards_and_current("3 boards", 0));
list_of_boards.add(new boards_and_current("4 boards", 0));
list_of_boards.add(new boards_and_current("5 boards", 0));
list_of_boards.add(new boards_and_current("6 boards", 0));
list_of_boards.add(new boards_and_current("7 boards", 0));
list_of_boards.add(new boards_and_current("8 boards", 0));
}
@Override
public String toString() {
return this.boards + "-" + this.current;
}
}
在这里,我得到了不同组合板的总电流,并为“当前”字段分配了新值
boards_and_current list = new boards_and_current("",0);
list.addBoards();
for (int i=2; i<=8; i++) {
for (boards_and_current a: list_of_boards) {
a.current = mA_per_board * i;
}
}
输出是[2个板1192、3个板1192、4个板1192、5个板1192、6个板1192、7个板1192、8个板1192]
但应该是这样的:[2个板-298、3个板-447、4个板-596、5个板-745、6个板-894、7个板-1043、8个板-1192]
知道为什么只有最后一个值被分配给数组中的所有元素吗?
提前感谢您!感谢您的帮助:)
【问题讨论】:
-
旁注:请遵循 Java 命名约定
标签: java for-loop arraylist constructor