// getting exception in thread main error in result[row][col]= arrayfirst [row][col] + arraysecound [row[col];
public class apples
public static void main(String args[])
{
int arrayfirst[] [] ={{1,2,3},{2,3,4}};
int arraysecound[] [] ={{3,4,5},{6,7,8}};
int result[][]= new int [2][2];
for(int row =0; row<arrayfirst.length; row++)
{
for(int col =0; col<arrayfirst[row].length; col++)
{
result[row][col]= arrayfirst [row][col] + arraysecound [row][col];
}
}
for(int row =0; row<arrayfirst.length; row++) {
for(int col =0; col<arrayfirst[row].length; col++) {
System.out.print(" "+result[row][col]);
}
System.out.println();
}
}
}
// BUT THESE SIMILAR PROGRAMS RUNS CORRECTLY WHY
public static void main(String args[])
{
int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};
int arrayC[][] = new int[4][4];
for(int i = 0; i < arrayA.length; i++) {
for(int j = 0; j< arrayA[0].length; j++) {
arrayC[i][j] = arrayA[i][j] + arrayB[i][j];
// System.out.print(arrayC[i][j] + " ");
} // end j for loop
} // end i for loop
for (int i = 0; i < arrayC.length; i++) {
for (int x = 0; x < arrayC[i].length; x++) {
System.out.print(arrayC[i][x] + " | ");
}
System.out.println();
}
} // end main
} // end class
答案 0 :(得分:1)
int arrayfirst [] [] = {{1,2,3},{2,3,4}}; int arraysecound [] [] = {{3,4,5},{6,7,8}};
这里,arrayfirst和arraysecound包含两行和三列,每行 (用逗号分隔的内部花括号的数量表示行数,在这些内部花括号内写的数字表示列数) , 所以当你添加他们的元素并尝试存储结果时,你再次需要一个有两行三列的数组。
所以,只需替换
int result [] [] = new int [2] [2]; 同 int result [] [] = new int [2] [3];
答案 1 :(得分:0)
第一个程序中的结果数组太小了。
答案 2 :(得分:0)
更改以下
int result[][]= new int [2][2];
到
int result[][]= new int [2][3];
另外,要了解有关java中数组的更多信息,请查看http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html