0

这是我要解决的问题:

编写一个名为 的类ArrayHistogram,其中包含一个 main 方法和一个名为 histogram 的静态方法,其签名如下: public static int[] histogram(int[][] arrayA) 在 main 方法中,声明并初始化一个二维数组,调用它arrayA。该数组必须包含一些非负整数。histogram 方法接受arrayA元素的出现频率并将其arrayA放入一维数组 ( histA) 中并返回histA。出现频率是指一个元素在数组中出现的次数。您的程序也应该适用于参差不齐的数组。histA在声明变量之前,您的程序应该自动确定 的大小histA

提示:图 1 显示了一个示例 2D 数组 ( arrayA) 和对应的histA. histA[0] = 2表示 0 在 A 中出现了两次。或者,histA[3] = 1表示数字 3 在 A 中出现了一次。

到目前为止我已经这样做了

public class ArrayHistogram
{
    public static void main (String[]args)
    {
        // declearing and initializing a 2D array.
        int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
        histogram(arrayA);

    }
    public static int[] histogram (int [][] arrayA)
    {  // nested for loop to go through the array.
        int max = 0;
       for ( int row = 0; row<arrayA.length; row++){
           for ( int col=0; col < arrayA[row].length; col++){

               if ( arrayA[row][col]> max ){
                   max = arrayA[row][col];
            }
        }
    }
    int histA[] = new int [max];
    for ( int row = 0; row<arrayA.length; row++){
           for ( int col=0; col < arrayA[row].length; col++){
               histA[arrayA[row][col]]++;
            }
        }
        System.out.println(histA);
        return histA;
    }
}

这一行:

histA[arrayA[row][col]]++;

显示一个java.lang.ArrayIndexOutOfBoundsException

首先我这样做对吗?

如果不是,我应该如何实现?

4

2 回答 2

0

length是返回大小的数组对象的属性。现在,由于您从 0 开始循环数组到length数组,它指的是甚至不存在的数组索引。因此一个ArrayIndexOutOfBoundException.

只需将for循环终止表达式更新为arrayA.length-1andarrayA[row].length-1就可以了。

同样对于所有这些,exceptions只需检查他们的Java Doc,您就会得到答案。

于 2013-01-31T03:39:32.910 回答
0

请记住,数组的索引从 开始0,因此您的max值不会成为histA数组中可用的索引。解决此问题的一种方法是像这样创建您的数组:

int histA[] = new int[max + 1];

在您的第二个循环中,当您点击rowbeing2colbeing时4,它将尝试使用histA[9]which 不是该数组中的有效索引,除非您将数组定义为 size 10,在您的情况下为max + 1.

于 2013-01-31T03:28:43.877 回答