在我的 JAVA 代码中,我得到了一个数据,我必须找到模式。一切都成功编译,每种方法都有效。但是,当我尝试访问该模式时,我会java.lang.ArrayIndexOutOfBoundsException: 987
在终端窗口中看到一个。突出显示的部分在以下方法中,这是我的最大方法之一。顺便说一句,数据数组只是int []
数据。
public int maxOfData(int [] oa)
{
int max = oa[0];
for (int i = 1; i < size; i++)
{
if (oa[i] > max)
max = oa[i];
}
return max;
}
异常上线if(oa[i] > max)
模式代码是这样的:
public int[] modeOfData()
{
int[] tally = new int[maxOfData() + 1];
for( int i = 0; i < size; i++)
{
tally[data[i]]++;
}
//max contains frequency of modes
int max = maxOfData (tally);
int count = 0;
for( int i = 0; i < tally.length; i++)
{
if( tally[i] == max )
count++;
}
//count occurence of maxValue in tally (for)
//that determines how many modes there are
//declare another int called modes
int[] modes = new int[count];
//size of array should be count
//loop through tally and extract modes: it's the index value.
int pos = 0;
for( int i = 0; i < tally.length; i++)
{
if(tally[i] == count)
modes[pos++] = i;
}
return modes;
//modes are where the values are == max
}
我的另一个最大值data
是相同的,但data
不是oa
. 据我的老师说,我需要两种最大方法,就像那样。那我该怎么办?我该如何解决?