这是我要解决的问题:
编写一个名为 的类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
首先我这样做对吗?
如果不是,我应该如何实现?