Reputation: 57
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
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
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
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
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 char
s 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 char
s are added as you expect, e.g.:
System.out.println("" + board[0][0] + board[0][1] + board[0][2]);
Upvotes: 3