I got an error as you can see below...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Rectangle rGreenBorder[] = new Rectangle[greenBorder.length]; for (int i = 0; i < greenBorder.length; i++) { Border border = (Border) greenBorder[i]; rGreenBorder[i] = border.getBounds(); if (rPlayer.intersects(rGreenBorder[0])) { player.setX(player.getWidth() + 15); } if (rPlayer.intersects(rGreenBorder[1])) { player.setX(BOARD_WIDTH - player.getWidth() - 15); } if (rPlayer.intersects(rGreenBorder[i])) { player.setX(BOARD_WIDTH - player.getWidth() - 15); } } |
Actually, I think I might have found your error here. First, you start be initializing the loop here...
Rectangle rGreenBorder[] = new Rectangle[greenBorder.length]; |
Then you enter the loop, and initialize the first variable here...
1 2 3 4
| for (int i = 0; i < greenBorder.length; i++) { Border border = (Border) greenBorder[i]; rGreenBorder[i] = border.getBounds(); ... |
But, since you do this within the loop, only the rGreenBorder[0] is initialized. Your NPE error has to be here...
1 2 3 4 5
| ... if (rPlayer.intersects(rGreenBorder[1])) { player.setX(BOARD_WIDTH - player.getWidth() - 15); } |
because you never got around the second iteration of the loop to initialize that variable. To fix... it is actually pretty easy, just do this instead...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Rectangle rGreenBorder[] = new Rectangle[greenBorder.length]; for (int i = 0; i < greenBorder.length; i++) { Border border = (Border) greenBorder[i]; rGreenBorder[i] = border.getBounds(); if (rPlayer.intersects(rGreenBorder[0])) { player.setX(player.getWidth() + 15); } if( i > 0){ if (rPlayer.intersects(rGreenBorder[1])) { player.setX(BOARD_WIDTH - player.getWidth() - 15); } } if (rPlayer.intersects(rGreenBorder[i])) { player.setX(BOARD_WIDTH - player.getWidth() - 15); } } |
I've realized the compiler usually has a hard time pin-pointing these errors in arrays. I usually do breakpoints to find out exact position of errors. In this case, it is just that you checked a variable within a loop that wasn't initialized yet.