Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to print a two dimensional char array

I need to create a boardgame and
the output of the array needs to look like this:

desired output

But the output of my code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        }
    }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading