【问题标题】:Only one value is assigned to all arraylist elements in constructor构造函数中的所有arraylist元素只分配一个值
【发布时间】: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


【解决方案1】:

你的 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);
} 

【讨论】:

  • 您的代码带有 throw IndexOutOfBoundsException。您需要在for 循环条件中检查list_of_boards 的大小。
  • 不应该是list_of_boards.get(i - 2)吗?
  • 好的,我会解决的。
  • 谢谢,它成功了 :) 删除了增强的 for-loop 并使用了 i-2
猜你喜欢
  • 2019-09-26
  • 2018-02-09
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
相关资源
最近更新 更多