Java 我的BoundsException系列的来源是什么?
这是我的代码,其要点是编写一个程序,将1到10之间的20个数字随机输入到5行4列的二维数组中。程序应该输出二维数组,以及每行和每列的和。我不知道我从哪里得到这个异常这是我的总输出:Java 我的BoundsException系列的来源是什么?,java,arrays,exception,Java,Arrays,Exception,这是我的代码,其要点是编写一个程序,将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.ArrayI
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);
}
看看这个循环:
for(int col = 0; col < array.length; col++){
for(int row = 0; row < array[0].length; row++){
sumC += array[row][col];
}
请注意,这里我是如何从0运行到array.length-1的,并被用作表达式数组[i][j]中的第一个索引位。您自己应该能够相当轻松地调试它。。。 问题出在上一个嵌套for循环中 你说sumC+=array[row][col], 但是您的行变量是在循环内部声明的,您需要将其切换到
sumC += array[col][row];
第96行是哪一行?对我来说没问题。但是在最后一个for循环中,您不希望使用array[row].length而不是array[0].length吗?除了关于调试和读取stacktrace的注释外,养成编写只做一件事并且做得很好的方法的习惯永远都不会太早。如果你的代码有这样的方法,那么找到bug的来源就很容易了。@pearbear:自从你第一次问这个问题以来,你是否悄悄地改变了你的帖子?你的最后一个循环——有问题的循环——自从你问起就已经改变了,这使得我的答案看起来不正确。如果你想改变问题,请说清楚…@JonSkeet不,我没有。。。我在一个类中,所以他们希望我重新编写方法。我是初学者。。不,我不能在我的类中使用调试器
sumC += array[col][row];