Java 构造函数中的所有arraylist元素只分配一个值

Java 构造函数中的所有arraylist元素只分配一个值,java,for-loop,arraylist,constructor,Java,For Loop,Arraylist,Constructor,我需要计算每个电路板的mA,得到总电流,然后将该值分配给不同的电路板组合,以便将来进行比较和选择。问题是,当我想为数组分配新的计算值时,只分配最后一个值 这是我的构造函数: class boards_and_current{ public String boards; public int current; public boards_and_current(String boards, int current){ this.boards = boards;

我需要计算每个电路板的mA,得到总电流,然后将该值分配给不同的电路板组合,以便将来进行比较和选择。问题是,当我想为数组分配新的计算值时,只分配最后一个值

这是我的构造函数:

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;
    }
}
类板\u和\u当前{
公共弦板;
公共电流;
公用板_和_电流(串板、int电流){
这个。板=板;
这个电流=电流;
}
公共静态ArrayList list_of_boards=新ArrayList();
公共广告牌(){
列出_板的_。添加(新板_和_当前板(“2板”,0));
列出所有板。添加(新板和当前板(“3个板”,0));
列出所有电路板。添加(新电路板和当前电路板(“4个电路板”,0));
列出所有板。添加(新板和当前板(“5板”,0));
列出所有板。添加(新板和当前板(“6板”,0));
列出所有板。添加(新板和当前板(“7板”,0));
列出所有配电盘。添加(新配电盘和当前配电盘(“8个配电盘”,0));
}
@凌驾
公共字符串toString(){
返回this.boards+“-”+this.current;
}
}
在这里,我得到不同组合电路板的总电流,并给“电流”字段指定新值

boards_和_current list=新的boards_和_current(“,0);
list.addBoards();

for(int i=2;i您的for循环是问题所在。您将遍历整个电路板列表两次。您不需要增强的for循环。最后一次,当
i
为8时,您遍历整个列表,并最终使用相同的i值设置所有内容。尝试以下操作:

for (int i = 0; i < list_of_boards.size(); i++) {
  var a = list_of_boards.get(i); //You can get a using i, you don't need the enhanced for loop
  a.current = mA_per_board * (i + 2);
} 
for(int i=0;i
您的for循环是问题所在。您将遍历整个电路板列表两次。您不需要增强的for循环。最后一次,当
i
为8时,您遍历整个列表,并最终使用相同的i值设置所有内容。尝试以下操作:

for (int i = 0; i < list_of_boards.size(); i++) {
  var a = list_of_boards.get(i); //You can get a using i, you don't need the enhanced for loop
  a.current = mA_per_board * (i + 2);
} 
for(int i=0;i
旁注:请遵循Java命名约定旁注:请遵循Java命名约定使用throw
IndexOutOfBoundsException
执行您的代码。您需要检查
循环条件下
中的
单板列表的大小。这不应该是
单板列表吗。获取(i-2)
?好的,我会解决这个问题。谢谢,它成功了:)删除了增强for循环,并将I-2代码与throw
IndexOutOfBoundsException一起使用。你需要检查
循环条件下
列表中的
电路板的大小。这不应该是
列表中的电路板吗?获取(i-2)
?好的,我会修复它。谢谢,它工作了:)删除了增强的for循环并使用了i-2