2013-11-15 83 views
-1

在我的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。據我的老師說,我需要兩種最大的方法,就像那樣。那麼我該怎麼做?我該如何解決?

+0

訪問模式是什麼意思?函數調用modeOfData()? – SimplyPanda

+1

** size **是指什麼? 'maxOfData(int [] oa)'中的 – iShaalan

+0

'檢查數組的邊界條件。還有什麼是「尺寸」? – Nishant

回答

1

我覺得行

for (int i = 1; i < size; i++) 

應該

for (int i = 1; i < oa.length; i++) 
+0

索引'0' – Keerthivasan

+0

那麼,在他的代碼0已經分配給max –

+0

如果這是問題,爲什麼不只是返回oa.length而不是返回最大值? – Baby

0

ArrayIndexOutOfBound異常被拋出,指示數組已經用非法索引訪問。索引或者是負數,或者大於或等於數組的大小。每當你迭代一個數組對象。您需要遍歷在檢查指標總是比其長度

例如較小,

for(int i=1;i<array.length;i++){ 
    //access array content in ith position 
    System.out.println(array[i]); 
    } 

你的大小變了一個非法的數組索引值。這就是問題

+0

在循環OP之前將oa [0]賦值給max,不需要從0開始 –

+0

改變了它,只是想到了這個例外.. – Keerthivasan

0

看看存儲在大小中的數字,然後檢查看看你聲明oa[]的大小是多少。如果尺寸大於oa[]的尺寸,那麼你有問題。

0

問題是在這部分代碼

int max = oa[0]; 

for (int i = 1; i < size; i++) 
{ 
    if (oa[i] > max) 

    max = oa[i]; 
} 

重寫方法maxOfData(int [] oa)與適當的檢查這樣

public int maxOfData(int[] oa) { 
    if (oa == null) { 
     throw new IllegalArgumentException("Input array is null"); 
    } 
    int max=oa[0]; 
     for (int i = 1; i < oa.length; i++) { 
      if (oa[i] > max) 
       max = oa[i]; 
     } 
    return max; 
} 

如果輸入數組爲空它不應該被處理。

+0

在OP的代碼中,我們不知道'size'是什麼。它可能小於'oa.length',這意味着你的代碼會計算出與預期不同的東西。 –

+0

表示同意,它可能是數組中堆的大小(堆表示爲數組)。可以應用額外的檢查,但對於給定的問題,關於'size'變量沒有什麼說的 – Nishant

+0

我個人認爲上面的代碼很混亂。 a)不需要「其他」b)與OP一樣。將oa [0]分配給最大值,然後循環清晰易讀。 –

相關問題