這裏是我的代碼,其中的一點是編寫一個程序,該程序隨機地將1到10個20個數字輸入到5行和4列的2維數組中。程序應該輸出二維數組,每行的總和和每列的總和。我想不通的地方我得到這個異常(這是我的總輸出):我的ArrayOutOfBoundsException的來源是什麼?
Project 3...
2D Array elements: 6, 6, 7, 10, 4, 4, 0, 9, 0, 1, 3, 10, 1, 10, 10, 9, 10, 5, 8, 2,
Sum of Rows: 115
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at arrayProject.projectthree(arrayProject.java:96)
at arrayProject.main(arrayProject.java:19)
這裏是我的代碼:
public static void projectthree(){
System.out.println("Project 3...");
/*Write a program that randomly inputs 20 numbers from 1 to 10 into a 2-D array of 5 rows and 4 columns.
The program should output the 2-D array, the sum of each row storing numbers in a parallel array and
the sum of each column storing numbers in a parallel array*/
int array[][] = new int[5][4];
Random randomizer = new Random();
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = randomizer.nextInt(11); //Assign random values to each element in the array
}
}
System.out.print("2D Array elements: ");
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
System.out.print(" " +array[i][j]+ ","); //Output 2D Array
}
}
int[] sumOfRows = new int[array.length];
int[] sumOfColumns = new int[array[0].length];
int sumR = 0;
int sumC = 0;
for(int row = 0; row < array.length; row++){
for(int col = 0; col < array[0].length; col++){ //Sum of rows
sumR += array[row][col];
}
sumOfRows[row] = sumR;
}
System.out.println(" ");
System.out.println("Sum of Rows: " + sumR);
for(int col = 0; col < array.length; col++){
for(int row = 0; row < array[0].length; row++){
sumC += array[row][col];
}
sumOfColumns[col] = sumC;
}
System.out.println("Sum of Columns:" + sumC);
}
你試過調試它嗎? – BNL
哪條線是'96'線? – paislee
對我來說運行良好。但在最後一個for循環中,你不想array [row] .length而不是array [0] .length? –