【发布时间】:2014-06-17 16:51:55
【问题描述】:
// 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
【问题讨论】:
-
仔细查看
result数组的大小 -
在第一个示例中,
arrayFirst是2 x 3矩阵,但result是2 x 2,因此失败。
标签: java exception exception-handling main