Dan
Dan

Reputation: 53

Index out of bounds exception in homework

I'm trying to do a homework assignment. I have to use dynamic programming to display whether the next person to move is in a win/loss state. I don't need help with the actual problem, I need help with an index out of bounds exception I'm getting that baffles me. I'm only going to paste part of my code here, because I only need the for loops looked at. I also don't want anyone in my class seeing all my code and copying it. If you need more data please let me know. So here is the code:

if(primeArray[x] == true){
    for(int i = 1; i <= x; i++){
        if(primeArray[i]== true){
            newRowNumber = x - i;
        }
        if(dynaProgram[newRowNumber][columnNumber] < minimum){
            minimum = dynaProgram[newRowNumber][columnNumber];
        }
    }
}
//COMPOSITE CASE FOR X!
else{
    for(int k = 1; k <= x; k++){
        if((primeArray[k] == false)){
            newRowNumber = x - k;
        }
        if(dynaProgram[newRowNumber][columnNumber] < minimum){
            minimum = dynaProgram[newRowNumber][columnNumber];
        }
    }

For some reason the if(primeArray[i] == true runs correctly, but I'm getting index out of bounds exception on if(primeArray[k] == false. The only difference between these two is the use of the variable k over i in the for loop.(the for loops are identical) I haven't used either variables anywhere else in my code. I have no idea why this occurs for one but not the other. In both cases, x remains the same number.

I am also getting an index out of bounds exception on the second minimum = dynaProgram[newRowNumber][columnNumber], while the first doesn't encounter an error. I know it's probably a stupid error, but I can't figure it out. If I change the 'k' for loop to k < x the index of out bounds exception in the if(primeArray[k] == false line goes away, but then it isn't correct. (The error on the second minimum = dynaProgram[newRowNumber][columnNumber] doesn't go away however.)

All this code is in a nested for loop which iterates through the rows and columns in the table to fill them in. If I remove the above code and just put dynaProgram[rowNumber][columnNumber] = 1 I don't have an issue, so I don't believe that is the problem.

Upvotes: 2

Views: 376

Answers (1)

Chris Gerken
Chris Gerken

Reputation: 16392

When accessing an array of length 5 (for example)

int[] fred = new int[5];

the first element will be fred[0] and the last will be fred[4]

So when doing something like:

    if(primeArray[i]== true){

Make sure that i is less than the array length. Using a value of i equal to the array length will throw an exception.

Upvotes: 0

Related Questions