Doubt concerning arrays
Hello.
When I try to print a two-dimensional array, null positions comeback as squares. Why is this? What is wrong with my code?
char[][] board=newchar [15][15];
for(int i=0; i < 15;i++)
{
board[i][i] ='x';
}
for(int i=0; i < 15; i++)
{
for(int j=0 ; j < 15 ; j++)
{
if(board[i] ==null && board[j] ==null )
{
System.out.print(" ");
}
else
{
System.out.print(board[i][j] +" ");
}
}
System.out.println();
}
Thanks in advance for your help.
[1366 byte] By [
blasha] at [2007-11-26 13:55:58]

An array of char values cannot have positions whose value is null--char is a primitive.
Your 'j' loop is looking at the same values as your second 'i' loop. Namely, the one-dimensional arrays that make up the two-dimensional array.
Your 'j' loop's first line should be:
if (board[i][j] == 0)
You may want to print two spaces for that, so that the other values line up (depends on what you want your display to look like, of course).
> Hello.
> When I try to print a two-dimensional array, null
> positions comeback as squares. Why is this? What is
> wrong with my code?
>
> char[][] board= new char [15][15];
>
> for(int i=0; i < 15;i++)
> {
> board[i][i] = 'x';
> }
Now the diagonal from (0,0) to (14,14) gets filled 'x', the rest is filled with (char)0.
> for(int i=0; i < 15; i++)
> {
> for(int j=0 ; j < 15 ; j++)
> {
> if(board[i] == null && board[j] == null )
> {
> System.out.print(" ");
> }
> else
> {
> System.out.print(board[i][j] + " ");
> }
> }
> System.out.println();
> }
board[i] or board[j] are never null so the lineSystem.out.print(board[i][j] + " ");
is always called. Try printing this:System.out.print((char)0);
> Thanks in advance for your help.
You're welcome.