Home > Back-end >  I need to print a two dimensional char array
I need to print a two dimensional char array

Time:11-17

I need to create a boardgame and the desired output

current output

How can i get rid of those signs and make it look like the output I need?

And this is my code for it:

private char[][] boardMatrix;

    public TryingSth() {
        boardMatrix = new char[3][3];
//        boardMatrix[0][0] = 'H';

        for (int i = 0; i < boardMatrix.length; i  ) {
            for (int j = 0; j < boardMatrix.length; j  ) {
                if (i==0 && j==0){
                    System.out.print('H');
                } else if (i ==2 && j==2){
                    System.out.print('G');
                }else
                boardMatrix[i][j] = '_';
                System.out.print(boardMatrix[i][j]   " ");
            }
            System.out.println();
        }
    }

CodePudding user response:

You're printing boardMatrix[i][j] on every loop iteration. However, if you look closer, you'll see that you set the value of boardMatrix[i][j] only when it is equal to _. Therefore when you want to print 'H' or 'G', the value of boardMatrix[i][j] it not initialized, there is just some random bytes, so this character is printed as a crossed box (character with this code is non-printable).

You need to change lines System.out.print('H'); and System.out.print(G'); to boardMatrix[i][j] = 'H'; and boardMatrix[i][j] = 'G'; accordingly.

  • Related