user1736164
user1736164

Reputation: 49

I keep getting ArrayIndexOutOfBoundsException and I have no idea why

I keep getting the ArrayIndexOutOfBoundsException in the line that says winVals[i] = rand, but i have no idea why.

int valueCount = 5;
int theLimit = 5;
int[] winVals = new int[valueCount];
Random r = new Random();
int rand = 0;
for(int i= 0; i < winVals.length; i++)
{
    rand = r.nextInt(theLimit - 1) +1;
    if(i == 0)
    {
        winVals[0] = rand;
    }
    else if (i > 0)
    {
        for (int j = 0; j < winVals.length; j++)
        { 
           if( winVals[j] == rand)
           {
              i--;
           }      
           else
           {
               winVals[i] = rand;
           }
        }
    }
}
for(int i=0; i < valueCount; i++)
{
    System.out.println(winVals[i]);
}

Upvotes: 0

Views: 112

Answers (4)

r0ast3d
r0ast3d

Reputation: 2635

Just tested it , because of the above mentioned where the index is decremented, this runs in an endless loop.

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34387

I think this line is the problem.

   if( winVals[j] == rand)
     i--;

Think if before this line, i=0 and j=0, and this condition becomes true, i becomes, -1

Upvotes: 0

Brendan Long
Brendan Long

Reputation: 54312

for (int j = 0; j < winVals.length; j++)
{ 
   if( winVals[j] == rand)
       i--;
   else
   {
       winVals[i] = rand;
   }
}

In this section you're looping through values of j and decreasing i, but you're not bothering to check if i is still valid. What if i is 1 and you decrease it twice?

Upvotes: 6

P.P
P.P

Reputation: 121427

You decrement the loop counter inside the loop:

if( winVals[j] == rand)
     i--;

which leads to out of bounds.

Upvotes: 1

Related Questions