Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

This loop should not run, right?

while((col+i<=10 && mP2Board[row][col+i]!='~' && i<5)){ if(mP2Board[row][col+i] == 'X'){ undiscoveredHits += 1; } else if(mP2Board[row][col+i] == 'H'){ alreadyHit += 1; } i++; }

This is a loop in my Java-program. I am making a Battleship game, and this is one of like 8 loops to check the coordinates around the one you hit.

Anyway, when I enter the coordinate: row=0 and col= 7, 8 or 9, the program crashes!! And I just can't figure out why!

There are two gameboards in my program, but the error only occurs on the first board!

If you need any more code, I will provide it.

The error I get is btw: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

I'm trying to access a 2d array with 10 elements in both dimesions: char[10][10]

Hope anyone can solve this silly case!

  • Henning

Hah! I fixed it! How could I be so blind! I allowed col+i to be 10! Which is out of bounds. Sweet!