0

I'm making a pokemon type matchup calculator(water beats fire etc.) and I've come upon a rather strange bug. I'm iterating through an ArrayList containing all the weaknesses of that pokemon and comparing them to all of the resistances in order to see if any of them cancel out. Here's the repository for it on GitHub. The exception is being thrown on line 140 of src/main/Pokemon.java. I've accounted for the index changing when an item is removed, but still no luck. Here's the offending loop:

//Check 2x weakness v 2x Resist
eDiff = 0;
rDiff = 0;
for (int e = 0; e < effective.size()-eDiff; e++) {
    for (int r = 0; r < resist.size()-rDiff; r++) {
        if (effective.get(e-eDiff).equals(resist.get(r-rDiff))) {
            effective.remove(e-eDiff);
            resist.remove(r-rDiff);
            eDiff++;
            rDiff++;
        }
    }
}

Any thoughts?

Jacob
  • 363
  • 4
  • 12
  • 2
    http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Tunaki May 05 '16 at 22:43

2 Answers2

2

For example when rDiff becomes 1 you can see that r-rDiff can be negative and the get cause the error.

You should modify that cycle whitout using eDiff and rDiff in it.

I think something similar should work:

for (int e = 0; e < effective.size(); e++) {
    for (int r = 0; r < resist.size(); r++) {
        if (effective.get(e).equals(resist.get(r))) {
            effective.remove(e);
            resist.remove(r);
            e--;
            break;
        }
    }
}
Loris Securo
  • 7,538
  • 2
  • 17
  • 28
  • That will not work at all. It will still throw an exception because e will become less than one. r will also just stay at 0 – sbowde4 May 05 '16 at 23:37
  • `e` only increments when the first for loops is run. There for, `e--` will execute during each iteration of the second loop, making `e` negative. `r` increments in the beginning of the second for loop, then becomes 0 at the end again. This creates an infinite loop – sbowde4 May 05 '16 at 23:43
1

You problem is in your second for loop, you are incrementing ediff on every run while e will not increment till the second for loop has finished this gives you

0 - ediff = -x

a negative integer is not a valid index for an array.

Try this if both arrays are the same size.

for (int i = 0; resist.size(); i++){// I increments by one each time
      if (effect.get(i) == resist.get(i)){//gets the value at index 1 through I, and compares them
          effective.remove(i);//removes them if they are equal
          resist.remove(i);
      }

  }
sbowde4
  • 767
  • 1
  • 4
  • 23