gpt4 book ai didi

java - java.lang.ArrayIndexOutOfBoundsException : 问题

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:31 25 4
gpt4 key购买 nike

我正在尝试计算 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;
}
}

最佳答案

computeRowSums中,您得到的索引顺序错误。应该是:

    for(i = 0; i < arr[0].length; i++) 
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[j][i];

我假设您的二维数组具有不同的行数和列数,这解释了您遇到的异常。

关于java - java.lang.ArrayIndexOutOfBoundsException : 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com