在我的JAVA代碼中,我得到一個數據,我必須找到模式。一切順利編譯,每一種方法都有效。但是,當我嘗試訪問該模式時,我的終端窗口中出現java.lang.ArrayIndexOutOfBoundsException: 987
。突出顯示的部分在以下方法中,這是我的最大方法之一。順便說一句,數據數組只是int []
數據。爲什麼我收到ArrayIndexOutofBoundsException?
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
。據我的老師說,我需要兩種最大的方法,就像那樣。那麼我該怎麼做?我該如何解決?
訪問模式是什麼意思?函數調用modeOfData()? – SimplyPanda
** size **是指什麼? 'maxOfData(int [] oa)'中的 – iShaalan
'檢查數組的邊界條件。還有什麼是「尺寸」? – Nishant