0

I'm getting the error java.lang.reflect.InvocationTargetException whenever I use a loop, if I just create a rectangle and assign it to an array, it works but if I try to assign it in a loop this pops up. I tried to search it up but most answers revolved around an FXML file but I don't have one. Is it required? Would the error go away if I added one?

public class ChessBoard extends Application {

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        ChessBoard(primaryStage);
    }

    public void ChessBoard(Stage primaryStage) {
        primaryStage.setTitle("");
        Group root = new Group();
        Scene scene = new Scene(root, 520, 520, Color.WHITE);

        Rectangle [][]tiles = new Rectangle[4][4];

        for(int i = 0; i < tiles.length; i++) {
            for(int j = 0; j < tiles[i].length; i++) {
                tiles[i][j] = new Rectangle();
            }
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
Slaw
  • 37,820
  • 8
  • 53
  • 80
Exalino
  • 39
  • 6
  • 1
    An `InvocationTargetException` always has a _cause_ which can be found by looking at the `Caused by:`s in the [stack trace](https://stackoverflow.com/questions/3988788/). In your case, it's probably caused by an `ArrayIndexOutOfBoundsException` due to the fact you call `i++` instead of `j++` in your inner `for` loop. – Slaw Jun 18 '19 at 04:35
  • As an aside, I suggest renaming your `ChessBoard` method. Currently, it looks like a constructor due to having the exact same name as the class. Nor does it follow Java naming conventions—methods use `camelCase`. – Slaw Jun 18 '19 at 04:38

1 Answers1

1

Your mistake is tiny

just change this line

for(int j = 0; j < tiles[i].length; i++) {

to this one

for(int j = 0; j < tiles[i].length; j++) {

the problem is in the inner loop where you increase the counter variable ( i ) instead of the inner loop counter variable ( j ) which causes the integer ( i ) to go beyond the length of the array causing java.lang.ArrayIndexOutOfBoundsException: 4

Hope this works

Ibraheem Alyan
  • 426
  • 1
  • 5
  • 14