0 java arrays multidimensional-array
public class MatrixAddition {
public static void main(String[] args) {
int ar1[][] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
int ar2[][] = { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };
addArray(ar1, ar2);
}
private static void addArray(int[][] tmp1, int[][] tmp2) {
int[][] sum = {};
System.out.println(" ");
System.out.println("The sum of the two matrices is");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = tmp1[i][j] + tmp2[i][j];
System.out.print(sum[i][j] + " ");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
The sum of the two matrices is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Run Code Online (Sandbox Code Playgroud)
您唯一的问题是您没有sum正确初始化数组:
int[][] sum = new int[tmp1.length][tmp1[0].length];
Run Code Online (Sandbox Code Playgroud)
您将其初始化为空数组.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |