我正在尝试计算2D数组的行和列总和,但我总是收到此错误java.lang.ArrayIndexOutOfBoundsException:2
它说方法computeRowSums有一个错误,但我无法弄清楚为什么数组索引超出范围。
// RowColSums.java
// To compute the row and column sums of a 2D array.
import java.util.*;
public class RowColSums {
public static void main(String[] args) {
int row_size, col_size, row, col;
int[][] array2D;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows and columns: ");
row_size = sc.nextInt();
col_size = sc.nextInt();
array2D = new int[row_size][col_size];
System.out.println("Enter values for 2D array: ");
for(row = 0; row < row_size; row++)
for(col = 0; col < col_size; col++)
array2D[row][col] = sc.nextInt();
int[] rowSums = computeRowSums(array2D);
System.out.print("Row sums: ");
System.out.println(Arrays.toString(rowSums));
int[] colSums = computeColSums(array2D);
System.out.print("Column sums: ");
System.out.println(Arrays.toString(colSums));
}
public static int[] computeRowSums(int[][] arr)
{
int i, j;
int[] row_sum = new int[arr[0].length];
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[i][j];
return row_sum;
}
public static int[] computeColSums(int[][] arr)
{
int z, r;
int[] col_sum = new int[arr.length];
for(z = 0; z < arr.length; z++)
for(r = 0; r < arr[0].length; r++)
col_sum[z] += arr[z][r];
return col_sum;
}
}
答案 0 :(得分:0)
在computeRowSums
中,您的索引顺序错误。它应该是:
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[j][i];
我假设您的2D数组具有不同数量的行和列,这解释了您获得的异常。