0

I just moved recently to use java and after I learn some of the syntax I decided to write a chess game to teach myself more.

I'm trying to create an array of array of string to store the basic view of the board, but when I print it out everything is null.

private String board[][] = new String[8][8];

    public Board() {
        System.out.println("created");
        for (String[] row : board) {
            for (String cell : row) {
                cell = "-";
            }
        }
        printBoard();
    }

It's feel like I'm messing a bit with the for each or the string concept.

Thanks in advance,

Or

2 Answers 2

1
cell = "-";

This assignment is happening to the local variable declared in the for loop.

You need to access each of the element in the array and assign the String.

for (int i=0; i<board.length; i++) {
    for (int j=0; j<board[i].length; j++) {
        board[i][j] = "-";
    }
}

Here board.length is the number of String[] (rows) and board[i].length and number String in each array (column).

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

Comments

0

You should not use a forech loop to fill the array. Use a regular for loop instead. Change

for (String[] row : board) {
    for (String cell : row) {
        cell = "-";
    }
}

to

for(int i = 0; i < board.length; i++) {
    for(int j = 0; j < board[i].length; j++) {
        board[i][j] = "-";
    }
}

The foreach loop cannot modify the elements of the iterated array.

4 Comments

If you take a closer look, you will see that using a foreach loop, you are only modifying copies, not the real thing.
Ho...Thank. So I can use for each loop to copy and sort of staff, but not modifie the same loop?
Yes, in deed. (I think you should accept this answer instead, it's providing more details)
You can, however, keep your first for-each loop and use for(String[] row : board) for(int i = 0; i < row.length; i++) row[i] = "-";

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.