这是我的代码,其中的一点是编写一个程序,将1到10之间的20个数字随机输入到5行和4列的2-D数组中。程序应该输出2-D数组,以及每行的总和和每列的总和。我无法弄清楚我在哪里获得此例外(这是我的总输出):
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);
}
答案 0 :(得分:4)
看看这个循环:
for(int col = 0; col < array.length; col++){
for(int row = 0; row < array[0].length; row++){
sumC += array[row][col];
}
您正在访问array[row][col]
,但您应该访问array[col][row]
...或更改循环方式。将此循环与所有其他有效的循环进行比较:
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
System.out.print(" " +array[i][j]+ ",");
}
}
注意i
从0到array.length - 1
的运行方式,并用作表达式array[i][j]
中索引的第一位。
答案 1 :(得分:0)
你应该能够自己轻松调试这个...... 问题出在你最后一个嵌套for循环...
你说sumC += array[row][col];
,
但你的行变量是在循环内部声明的,你需要将它切换到
sumC += array[col][row];