2011-12-09 73 views
0

基本上,我有一項任務,需要我找到一組給定數字的模式。爲什麼我得到一個數組索引越界異常?

這是我的方法:

public void findMode(){ 
    /* The vector data is analyzed and transferred into a smaller vector 
    smallList (0..100). For each occurrence of n in vector data, 
    smallList[n] is incremented +1. function Largest is then called 
    to find the largest quantity in vector smallList. The mode(s) 
    is/are printed out. */ 

    int loop, largest; 
    int[] smallList = new int[101];  
    for (int i = 0; i < myHowMany; i++) 
    { 
     smallList[myData[i]]++; 
    } 
    int max = 0; 
    for (int i = 0; i < smallList.length; i++) 
    { 
     if (max < smallList[i]) 
     { 
      max = smallList[i]; 
     } 
    } 
//Max is 26 
    int size = 0; 
    for (int i = 0; i < smallList.length; i++) 
    { 
     if (i == max) size++; 
    } 

    int[] modes = new int[size]; 
    int modeIndex = 0; 
    for (int i = 0; i < smallList.length; i++) 
    { 
     if (smallList[i] == max) 
     { 
      modes[modeIndex] = smallList[i]; 
      System.out.println(modes[modeIndex]); 
      modeIndex++; 
     } 
    } Everything compiles fine, but when I run this method, I get an out of bounds array method. I have no idea WHY this happens so I 

需要知道,如果社會能幫助我

。 解決!

請告訴我,如果我需要更多的信息!

編輯:我忘了提,我來到這裏的錯誤:

modes[modeIndex] = smallList[i]; 

新的問題: 我從以前固定的問題,但是現在,我發現我的最大進獻給陣列,這樣的模式= 26(最大)

+0

嘗試並查看堆棧跟蹤,它應該打印導致超出範圍異常的索引 –

+0

編譯器是否告訴您哪一行提供IndexOutOfBoundsException? – Averroes

+0

對不起,我還沒有學到什麼棧跟蹤呢! – DSdavidDS

回答

2

你的錯誤是在這一行

if (i == max) size++; 

應該

if (smallList[i] == max) size++; 

這是造成modes大小是錯誤的

1

這應該足夠清楚:modeIndex或i超出數組大小。既然你用smallList.length循環了smallList,那麼我猜這個錯誤是在modeIndex中。在這種情況下,尺寸(用於構造模式)不夠大。

+0

謝謝!我基本上發現我必須增加數組[size]到[size + 1] – DSdavidDS

0

如果(我==最大)尺寸++; 然後 if(smallList [i] == max)

請檢查您的值的大小。