簡體   English   中英

為什么我得到數組索引超出范圍異常?

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

基本上,我的作業要求我找到給定數字集的模式。

這是我的方法:

  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(max)

您的錯誤在這一行

if (i == max) size++;

它應該是

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

這導致modes大小錯誤

這應該足夠清楚:modeIndex或i超出了數組大小。 由於您正在使用smallList.length遍歷smallList,因此我猜錯誤在於modeIndex。 在這種情況下,大小(用於構造模式)不夠大。

如果(i ==最大)size ++; 然后如果(smallList [i] == max)

請檢查您的值的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM