Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation not working as expected

Tags:

java

algorithm

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 is printing the following exit:

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

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

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

I can't figure out why its not running as expected.

like image 224
Victor Avatar asked Nov 28 '22 09:11

Victor


2 Answers

that's because you are adding ' ' to your variables, since ' ' is a character with asci code 32, it adds 32 to zero value inside your array and prints 32. you have to write two prints to have the output you formated as you like.

like image 178
Ali1S232 Avatar answered Dec 15 '22 01:12

Ali1S232


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

' ' is the character for whitespace, which has the ascii value 32. Single quotes denote a char value not a String

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

will concatenate a space.

like image 39
Brian Roach Avatar answered Dec 15 '22 02:12

Brian Roach