【发布时间】:2012-01-24 18:38:31
【问题描述】:
这是我的代码,其目的是编写一个程序,将 1 到 10 的 20 个数字随机输入 5 行 4 列的二维数组中。程序应该输出二维数组,以及每行的总和和每列的总和。我不知道我从哪里得到这个异常(这是我的总输出):
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);
}
【问题讨论】:
-
哪一行是
96行? -
对我来说运行良好。但是在最后一个for循环中,你不想要array[row].length而不是array[0].length吗?
-
除了关于调试和阅读stacktrace的cmets,养成编写只做一件事并做好的方法的习惯永远不会太早。如果你的代码有这样的方法,那么找到你的 bug 的来源就很容易了。
-
@pearbear:自从您第一次提出问题后,您是否默默地更改了您的帖子?你的最后一个循环 - 有问题的循环 - 自从你问它以来已经改变,使我的答案看起来不正确。如果您要更改问题,请说明清楚...
-
@JonSkeet 不,我没有...我在上课,所以他们希望我重写方法。我是初学者。不,我不能在课堂上使用调试器