【发布时间】: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