【问题标题】:How to reference a method that returns an array and assign a new value to the array?如何引用返回数组的方法并为数组分配新值?
【发布时间】:2021-06-30 16:12:42
【问题描述】:

我正在尝试从在同一类中返回数组的方法访问数组。然后我需要写回数组以供将来使用。这是到目前为止的代码:```

public int [] unitSelection(){
    int [] selectedUnits = new int[numberCheck()];

    return selectedUnits;

for (int i = 0; i < checkBoxList.length; i++) {
                    if (checkBoxList[i] == e.getSource()) {
                        index = i;
                        unitSelection()[i] = index;
                        export_to_SRF.setEnabled(true);
                    }
```

代码“unitSelection()[i]”应该在“unitSelected”方法中更新“selectedUnits”数组中的数组。我一直在阅读,但找不到与引用外部方法数组有关的任何内容。提前致谢

【问题讨论】:

  • 我目前正在返回一个空数组
  • 您得到一个空数组,因为unitSelection() 在每次调用时都会返回一个新数组。除非这只是本示例的虚拟方法体。

标签: java arrays methods reference


【解决方案1】:
for (int i = 0; i < checkBoxList.length; i++) {
   if (checkBoxList[i] == e.getSource()) {
      index = i;
      int[] x = unitSelection();
      x[i] = index;
      export_to_SRF.setEnabled(true);
   }

但我认为这不会达到你想要的效果。 unitSelection() 每次都会返回一个新数组,因此实际上不会更新数组。

【讨论】:

  • 感谢最后的响应,我移动了数组并将其公开给我的班级,因为我也在其他方法中使用它。
猜你喜欢
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
  • 2011-11-06
  • 2016-07-23
  • 2016-09-23
  • 2018-05-27
相关资源
最近更新 更多