Java游戏添加TileMap后触发ArrayIndexOutOfBoundsException问题排查求助
ArrayIndexOutOfBoundsException in Your Tile Map Code Hey there, let's break down that error you're hitting. The exception points straight to line 158 in TileMap.java: if(map[row][col] == 0) continue; — you're trying to access a row index that doesn't exist in your map array.
What's Going Wrong?
Your draw loop runs from rowOffset to rowOffset + numRowsToDraw, but you don't check if row goes beyond the total number of rows in your map (numRows). For example, if your map has 8 rows (indices 0 through 7), once row hits 8, accessing map[8][col] throws the out-of-bounds error. You added a check for columns (if(col >= numCols) break;), but missed the same guard for rows.
Quick Fix
Add a row bounds check inside the outer loop, or adjust the loop's upper limit to never exceed numRows. Here's the corrected draw method:
public void draw(Graphics2D g) { for (int row = rowOffset; row < rowOffset + numRowsToDraw; row++) { // Don't go past the last row of the map if (row >= numRows) { break; } for (int col = colOffset; col < colOffset + numColsToDraw; col++) { if (col >= numCols) { break; } if (map[row][col] == 0) { continue; } int rc = map[row][col]; int r = rc / numTilesAcross; int c = rc % numTilesAcross; g.drawImage(tiles[r][c].getImage(), (int)x + col * tileSize, (int)y + row * tileSize, null); } } }
Alternative Cleanup
If you prefer a tighter loop condition, you can use Math.min to cap the row index at numRows right in the loop declaration:
for (int row = rowOffset; row < Math.min(rowOffset + numRowsToDraw, numRows); row++) { // ... rest of the loop remains the same }
This way you don't need the extra break statement — the loop will automatically stop before hitting an invalid row index.
The root issue is that numRowsToDraw is calculated to include partial tiles off the screen, which can push the row index beyond your map's actual size when rendering near the bottom edge. Adding this guard ensures you only access valid indices in your map array.
内容的提问来源于stack exchange,提问作者TheNewOne

