Nikolaj Egholk Jakobsen Nikolaj Egholk Jakobsen - 2 months ago 16
Java Question

Java 2D Array for chess board not working

i'm trying to make a simple chess board with Strings as my chess pieces in a 8x8 2D Array. But the output is not what I want, as the Array just goes down. (Sorry for my language. I'm not so good at programming) Here's my code:

public class ChessBoard {
String[][] board = new String[8][8];
public void fillBoard() {
//Fills the empty spaces
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = " ";
}
}

// Rooks
board [0][0] = "R";
board [0][7] = "R";
board [7][0] = "R";
board [7][7] = "R";

// Knights
board [0][1] = "N";
board [0][6] = "N";
board [7][1] = "N";
board [7][6] = "N";

//Bishops
board [0][2] = "B";
board [0][5] = "B";
board [7][2] = "B";
board [7][5] = "B";

//Queens
board [0][3] = "Q";
board [7][3] = "Q";

//Kings
board [0][4] = "K";
board [7][4] = "K";


//Pawns
for (int i = 0; i < 8; i++) {
board[1][i] = "P";
board[6][i] = "P";
}
}

public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j]);
}
System.out.println();
}
}
}


The output is then something like:

R
N
B
Q
K
B
N
R

P
P
P
P
P
P
P
P

P
P
P
P
P
P
P
P

R
N
B
Q
K
B
N
R


But the intention was this output:

R N B Q K B N R
P P P P P P P P






P P P P P P P P
R N B Q K B N R


What am I doing wrong?

EDIT:
I have changed

public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j] + " "); //this line
}
System.out.println();
}
}


But nothing happens.

Answer

You're looking for:

public void presentBoard() {
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            System.out.print(board[i][j] + " ");
        }
        System.out.println();
    }
}

System.out.println() prints in a new line. On the other hand, there is System.out.print() which stays in the same line.

enter image description here

enter image description here