2011-12-09 142 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)

请检查您的值的大小。