Justin Beaubien
Justin Beaubien

Reputation: 57

How to display arrays

I'm trying to display a array board for my tic-tac-toe game.

The board is supposed to look like this:

123

456

789

However when I run the program it shows up like this:

150

159

168

My Code:

 class TicTacToe


{
    public static void main(String[] args)
    { 
       char [][] board = {{'1','2','3'}, {'4','5','6'}, {'7', '8', '9'}};

        System.out.println(board[0][0] + board[0][1] + board[0][2]);
        System.out.println(board[1][0] + board[1][1] + board[1][2]);
        System.out.println(board[2][0] + board[2][1] + board[2][2]);


   }
}

Upvotes: 4

Views: 333

Answers (4)

Daedric
Daedric

Reputation: 500

This is a much more efficient method (takes all the manual work out) that will blitz through larger array tables with ease and yours as well (it may look complex but give it a quick look):

class TicTacToe {
    public static void main(String[] args) { 
       char [][] board = {{'1','2','3'}, {'4','5','6'}, {'7', '8', '9'}};

        for (int i = 0; i < board.length; i++) {       //loop rows

           for (int j = 0; j < board[0].length; j++) { //loop columns
              System.out.print(board[i][j]);           //print columns
           }
           System.out.println();                       //print space for the next row
        }
   }
}

Upvotes: 1

MaxZoom
MaxZoom

Reputation: 7743

You are printing the sum of character code (see ASCI table) 1=49 2=50 3=51
49 + 50 + 51 = 150

To print character representation indicate the string concatenation as below:

class TicTacToe
{
   public static void main(String[] args)
   { 
     char [][] board = {{'1','2','3'}, {'4','5','6'}, {'7', '8', '9'}};
     System.out.println("" + board[0][0] + board[0][1] + board[0][2]);
     System.out.println("" + board[1][0] + board[1][1] + board[1][2]);
     System.out.println("" + board[2][0] + board[2][1] + board[2][2]);
   } 
}

Upvotes: 1

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

Those values you see are the addition/sum of the character in there decimal values in the ascii table:

'1' = 49
'2' = 50
'3' = 51

equals

150

What you need to do is add/append an empty string instead of adding the characters decimal value

System.out.println(board[0][0] +""+ board[0][1] + board[0][2]);

Upvotes: 5

rgettman
rgettman

Reputation: 178243

This is a consequence of the fact that the char values you're attempting to print are being added mathematically instead of being concatenated. The Unicode values of the chars representing the numbers '0' through '9' are 48 through 57, respectively.

So, adding '1', '2', and '3' means adding 49, 50, and 51, which sums to 150, which is printed.

Include an empty string at the beginning, so that String conversion takes place as the values are concatenated from left to right, and that the chars are added as you expect, e.g.:

System.out.println("" + board[0][0] + board[0][1] + board[0][2]);

Upvotes: 3

Related Questions