Reputation: 9
I was converting over a method that written for arrays to be used to find the mode for an ArrayList passed from main. Somewhere along the way I'm hitting and index error. Im sure its an obvious mistake, but just not seeing it. Would love another set of eyes on this!
public static int getMode(ArrayList<Integer> a)
{
int i ,j ,ctr=0 ,wantedScore ,maxsofar ,position=0 ,mode;
ArrayList<Integer> ctrArray = new ArrayList<>(a.size());
for(i=0; 1< a.size(); i++)
{
wantedScore = a.get(i);
for(j=i+1; j < a.size(); j++)
{
if(a.get(i)==wantedScore)
{
ctr++;
}//End IF
ctrArray.add(ctr);
}//End Inner Loop
}//End Outer For Loop
//Find highest value counter
maxsofar=a.get(0);
for(i=0; i< a.size(); i++)
{
if(ctrArray.get(i)>maxsofar)
{
maxsofar=ctrArray.get(i);
position=i;
}//End If
}//End For Loop
if(maxsofar>0)
mode=a.get(position);
else
mode=-1;
return mode;
}//End getMode
The error I'm getting if the Array list contains the values 1, 2, 3 is: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
Upvotes: 0
Views: 33
Reputation: 450
for(i=0; 1< a.size(); i++)
it should be for(i=0; i< a.size(); i++)
Upvotes: 5