【问题标题】:Assigning values to a 2D array using a nested for loop使用嵌套的 for 循环为二维数组赋值
【发布时间】:2021-06-09 22:19:06
【问题描述】:

我想通过使用嵌套的 for 循环将值迭代到我的二维数组,但这是我目前所拥有的。我认为它确实填充了我的二维数组,但没有填充我想要的数字。我希望它从 2 开始填充 2 的幂。所以我的结果看起来像: 2, 4, 8, 16、32、64.. 等等,直到我的行和列都完成。

我的代码:

public class RowsSum {
    public static void main(String[] args) {
        int[][] nums = new int[5][3]; //declaring a 2D array of type int
        for (int i = 0; i <= nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                nums[i][j] = (i * nums[0].length) + j + 1;
                System.out.print(nums[i][j] + "\t");
            }//closing inner loop
            System.out.println("");
        }// closing nested for loop
    }// closing main method
}//closing class

【问题讨论】:

  • 转换为一维索引(列 * 行 + 列)并将 2 提高到该次方。 nums[i][j] = Math.pow(2, nums[0].length * i + j)
  • 或者,保持 2 个变量的运行幂:int power2 = 1 然后在循环中:nums[i][j] = power2; power2 *= 2;
  • 非常感谢!这就是我要找的@JohnnyMopp

标签: java for-loop multidimensional-array


【解决方案1】:

这应该可行:

public class RowsSum {
  public static void main(String[] args) {
    int[][] nums = new int[5][3]; //declaring a 2D array of type int
    int num = 2;
    for (int i = 0; i < nums.length; i++) {
      for (int j = 0; j < nums[i].length; j++) {
        nums[i][j] = (int) Math.pow(num, ((i*nums[i].length)+j+1)); //code A
        System.out.print(nums[i][j] + "\t");
      }//closing inner loop
      System.out.println("");
    }// closing nested for loop
  }// closing main method
}//closing class

代码A:这里,我只是将数组里面的值设置为2的数组中位置的幂,从1开始。为了得到位置,我将当前col索引乘以每行的长度加上当前行中的索引。这只是一种方法,无需在循环外创建新的计数变量,然后每次在内循环中递增它,但如果您愿意,也可以这样做。

【讨论】:

  • 非常感谢!这也有帮助并且有效。 @RW77
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多