我有一个2D数组,其中行=3,列=2。我想得到所有指数的总和。这是我的阵列。
arr[][]=[1,2],[3,4],[5,6]
-
第1行
在
index (0, 0)
,索引的总和变为(0 + 0 = 0)
在
index (0, 1)
,索引的总和变为(0 + 1 = 1)
-
第2行
在
index (1, 0)
,索引的总和变为(1 + 0 = 1)
在
index (1,1)
,索引的总和变为(1 + 1 = 2)
-
第3行
在
index (2, 0)
,索引的总和变为(2 + 0 = 2)
在
index (2, 1)
,索引的总和变为(2 + 1 = 3)
我的预期输出变成
0 1 1 2 2 3
我找不到任何资源,如何做这个
另一个快速示例:
import java.util.*;
class Main {
public static void main(String[] args) {
int[][] arr = new int[3][2];
for(int row=0; row<arr.length; row++) {
for(int col=0; col<arr[row].length; col++) {
arr[row][col] = row + col;
}
}
for(int[] row : arr) {
System.out.println(Arrays.toString(row));
}
}
}
输出:
[0, 1]
[1, 2]
[2, 3]
您必须使用for循环或任何其他循环对列和行求和。
import java.util.*;
public class Main
{
public static void main(String[] args) {
int rows, cols, sumIndex = 0;
int a[][] = {
{1, 2},
{3, 4},
{5, 6}
};
rows = a.length;
cols = a[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
sumIndex = i + j;
System.out.print(sumIndex + " ");
}
}
}
}