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();
    }
}
2
  • 1
    An InvocationTargetException always has a cause which can be found by looking at the Caused by:s in the stack trace. 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. Commented Jun 18, 2019 at 4: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. Commented Jun 18, 2019 at 4:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.