String concatenation is not working properly

I have the following code:

public boolean prontoParaJogar() throws RemoteException { int i; int j; if (this.jogadores==2) { this.jogando=1; for (i=0;i<3;i++) for(j=0;j<3;j++) { this.tabuleiro[i][j]=0; } for (i=0;i<3;i++) { System.out.println("Linha "+i+": "); System.out.print(this.tabuleiro[i][0]+' '); System.out.print(this.tabuleiro[i][1]+' '); System.out.print(this.tabuleiro[i][2]); System.out.println(""); } return true; } else { return false; } } 

it prints the following output:

  Linha 0:
 32320
 Linha 1: 
 32320
 Linha 2: 
 32320
 Linha 0: 
 32320
 Linha 1: 
 32320
 Linha 2: 
 32320

This is not what I expected. This should be the following output:

  Linha 0:
 0 0 0
 Linha 1:
 0 0 0
 Linha 2:
 0 0 0

I can’t understand why it is not working as expected.

+4
source share
5 answers
 this.tabuleiro[i][0]+' ' 

' ' is a space character that has an ascii value of 32 . Single quotes mean char not a String

 this.tabuleiro[i][0]+" " 

will concatenate a space.

+10
source

because you add ' ' to your variables, since ' ' is a character with asci-code 32, it adds 32 to the zero value inside your array and prints 32. You need to write two fingerprints to have the output you formed on your own.

+12
source

You add 0 + 32 because `` is a space and 32 ASCII, instead of doing string concatenation. Change to

 System.out.print(this.tabuleiro[i][0]+" "); 
+6
source

In your output lines you use + ' ' . This adds the symbol '' (symbol value 32) to each tabuleiro entry. You need to use + " " .

+1
source

Also do not do this:

 for (i=0;i<3;i++) for(j=0;j<3;j++) { this.tabuleiro[i][j]=0; } 

but rather it:

 for (i=0;i<3;i++) { for(j=0;j<3;j++) { this.tabuleiro[i][j]=0; } } 

or at some point in the future you can do this:

 for (i=0;i<3;i++) System.out.println("i=" + i); for(j=0;j<3;j++) { this.tabuleiro[i][j]=0; } 

and be surprised that the second cycle does not run three times.

+1
source

All Articles