Dan White
Dan White

Reputation: 37

Changing an element of an array within an array in Java

I can't figure out how to change an element of an array within an array.

public class testOut{

public static void main(String[] args) {

    String board[][] = generate(7,7);

    print(board); // prints a 7x7 table with 49 "O"s

    board[2][2] = "X"; // This is the line I'm concerned about
    System.out.println(board[2][2]); // prints out "X"
    System.out.println(board[1][1]); // prints out "Null"

    print(board); // still prints a 7x7 table with 49 "O"s

}

static String[][] generate(int row, int column){


    String[][] board = new String[row+1][column+1];
    for (int x=0; x < row; x++){

        for (int y=0; y < column; y++){

            board[row][column] = "#";   
        }
    }
        return board;

}

static void print(String[][] board){

    int row = board.length - 1;
    int column = board[0].length - 1;

    for (int x=0; x < row; x++){

        for (int y=0; y < column; y++){
            System.out.print(board[row][column]);
        }
        System.out.println(""); 
    }

}
}

Output:

OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
X
null
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO

I'm trying to figure out -

Why am I able to print the "X" but my print function does not print the "X" on the table?

and

Why is my code able to correctly print out the table referencing each piece, but when I try to print an individual element, it gives null?

I'm guessing the two problems are related. It's working in the for loop, but not outside of the loop.

Upvotes: 0

Views: 80

Answers (2)

Dan White
Dan White

Reputation: 37

I was failing to use the iterator properly.

Upvotes: 0

Joe C
Joe C

Reputation: 15684

The array is being updated correctly. It's your printing that's wrong.

It's printing the last row, last column. Note how x and y in your loops are unused:

System.out.print(board[row][column]);

You can use the loop counters to print as :

System.out.print(board[x][y]);

Upvotes: 2

Related Questions