简体   繁体   中英

Why am I getting an array index out of bounds exception?

Basically, I have an assignment that requires me to find the mode of a given set of numbers.

This is my Method:

  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 

need to know if the community can help me

. Solved!

Please tell me if I need more information!

edit: I forgot to mention that I get the error here:

modes[modeIndex] = smallList[i];

New Problem: I fixed the problem from before, but now, I find that my max goes unto the array so that modes = 26(max)

Your error is in this line

if (i == max) size++;

It should be

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

This is causing the size of modes to be wrong

That should be clear enough: either modeIndex or i exceeds the array size. Since you're looping over smallList with smallList.length, I guess the error is in the modeIndex then. In this case, size (which is used to construct modes) isn't big enough.

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

Please check your value for size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM