Reputation: 23
Issue comparing str() to what I'd expect is their String form
Code :
int i = 2;
String r = str(i);
println(r);
if (r == "2") {
println("String works");
} else println("String doesnt work");
if (i == 2) {
println("Integer works");
} else println("Integer doesnt work");
Prints :
2
String doesnt work
Integer works
The second if statement is a copy paste of the first, with only the variable and value changed so theres nothing wrong with my if statement
Processing documentation states (about str()):
Converts a value of a primitive data type (boolean, byte, char, int, or float) to its String representation. For example, converting an integer with str(3) will return the String value of "3", converting a float with str(-12.6) will return "-12.6", and converting a boolean with str(true) will return "true".
Also doesnt work with str(2) == "2" or str(i) == "2"
How do I fix this and get it to work (without converting it back to an integer because that would make my code a bit ugly)
Upvotes: 0
Views: 109
Reputation: 42176
You should not compare String
values using ==
. Use the equals()
function instead:
if (r.equals("2")) {
From the reference:
To compare the contents of two Strings, use the
equals()
method, as inif (a.equals(b))
, instead ofif (a == b)
. A String is an Object, so comparing them with the == operator only compares whether both Strings are stored in the same memory location. Using theequals()
method will ensure that the actual contents are compared. (The troubleshooting reference has a longer explanation.)
More info here: How do I compare strings in Java?
Upvotes: 1