After reading your comments, I realized that it's not just about printing the array that you are concerned about; rather, you are concerned about how you will be able to access it later. The solution to the problem of incorrect printing has already been provided in the comments i.e. replacing System.out.print(Arrays.deepToString(board));
with System.out.print("X");
. I am explaining here the other part (i.e. how to access it later) and also some additional information that will help you in designing your application.
- When you pass and change an array in some method, the array will be changed for the calling method too (check this to learn more about it). It means that when
board[][]
will be changed in fillBoard
, you will get the changed board[][]
in main
.
- According to Single-responsibility principle, the module/method,
fillBoard
should do only one thing, which is filling up the board. It should not also do printing (additional thing). You should write a different method for printing.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[][] board = new String[7][7];
fillBoard(board);
displayBoard(board);
}
static void fillBoard(String[][] board) {
for (String[] row : board) {
Arrays.fill(row, "X");
}
}
static void displayBoard(String[][] board) {
for (String[] row : board) {
for (String cell : row) {
System.out.print(cell);
}
System.out.println();
}
}
}
Output:
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
Additional note:
A 2-D array is an array of 1-D arrays and therefore there are many ways in which you can write the code given above e.g.
static void fillBoard(String[][] board) {
for (int i = 0; i < board.length; i++) {
Arrays.fill(board[i], "X");
}
}
or using enhanced for
loop:
static void fillBoard(String[][] board) {
for (String[] row : board) {
Arrays.fill(row, "X");
}
}
or without using Arrays.fill
:
static void fillBoard(String[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = "X";
}
}
}
Similarly, the method, displayBoard
can be written as:
static void displayBoard(String[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
Note that I have used board.length
and board[i].length
instead of 7
for the number of rows and 7
for the number of columns to make sure you don't have to change it every time you change the size of the array.