Keys
Keys

Reputation: 3

If statement running when false

I'm attempting to write some code for a game in Java, however one of the if statements isn't working as expected.

if(player.gety() < y+row*tileSize){
    player.draw(g);
    System.out.println("Row:    " + y+row*tileSize);
    System.out.println("Player: " + player.gety());
}

When this code is run the output that I receive is:

Player: 200
Row:    -79.99999999968651320
Player: 200
Row:    -79.99999999968651320
Player: 200
Row:    -79.99999999968651320

This doesn't make much sense as player.gety() is clearly larger than y+row*tileSize. Is there any reason why this would be happening?

Upvotes: 0

Views: 79

Answers (2)

Jon Kiparsky
Jon Kiparsky

Reputation: 7773

String concatenation is what's tripping you up here. Specifically,

"Row:    " + y+row*tileSize

is not the same thing as

"Row:    " + (y+row*tileSize)

In the first case, you're getting

("Row:    " + y)+ (row*tileSize)

where y is being converted to its String representation and concatenated onto "Row: ", and then the product of row * tileSize is getting converted to its String representation and concatenated onto that.

In the second case, you'd be getting (y + row * tileSize), a single numeric value, which would then be turned into a String representation and concatenated onto the String "Row: :"

This is actually behaving as demanded by the spec. When either operand of the + operator is a String, it no longer means "addition", it means "concatenation", and concatenation does not obey the arithmetical rules of precedence. Instead, it greedily coerces its other operand to a String value and cats the two together.

This can have some unexpected results, as you've discovered. Try adding the parens as suggested above, or printing out the values of the variables individually:

System.out.println("y = "+ y + " row  = "+row + " tileSize = " + tileSize)

and it'll be easier to see what's happening.

EDIT: I expect that you'll find that More likely, y = -79.999999999 (ie, -79.9, repeating) and row*tileSize=68651320. Adding those up you get substantially more than 200.

Upvotes: 4

Grant Robinson
Grant Robinson

Reputation: 41

Yes, I don't think the Row output statement is showing what you think it's showing. Also, might player.draw(g) modify the result of player.gety()? Put the output statements first in the if-true block. Output each variable instead of an expression.

Upvotes: 0

Related Questions