Victor
Victor

Reputation: 1703

String concatenation not working as expected

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.

Upvotes: 4

Views: 397

Answers (5)

Adriaan Koster
Adriaan Koster

Reputation: 16209

Also don't do this:

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

but rather this:

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 might 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 loop is not being executed three times.

Upvotes: 1

Ali1S232
Ali1S232

Reputation: 3411

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.

Upvotes: 12

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31438

You are adding 0+32, because ' ' is space and that's 32 ASCII, instead of doing a string concatenation. Change to

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

Upvotes: 6

Ted Hopp
Ted Hopp

Reputation: 234817

In your output lines, you are using + ' '. This adds the character ' ' (character value 32) to each entry of tabuleiro. You need to use + " ".

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

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.

Upvotes: 10

Related Questions