转换为字符串的整数无法按预期工作
Integers converted to strings do not work as expected
将 str() 与我期望的字符串形式进行比较时出现问题
代码:
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");
打印:
2
String doesnt work
Integer works
第二个 if 语句是第一个的复制粘贴,只更改了变量和值,所以我的 if 语句没有任何问题
处理文档状态(关于 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".
也不适用于 str(2) == "2" 或 str(i) == "2"
我该如何解决这个问题并使其正常工作(不将其转换回整数,因为那样会使我的代码有点难看)
您不应使用 ==
比较 String
值。请改用 equals()
函数:
if (r.equals("2")) {
To compare the contents of two Strings, use the equals()
method, as in if (a.equals(b))
, instead of if (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 the equals()
method will ensure that the actual contents are compared. (The troubleshooting reference has a longer explanation.)
更多信息在这里:How do I compare strings in Java?
将 str() 与我期望的字符串形式进行比较时出现问题
代码:
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");
打印:
2
String doesnt work
Integer works
第二个 if 语句是第一个的复制粘贴,只更改了变量和值,所以我的 if 语句没有任何问题
处理文档状态(关于 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".
也不适用于 str(2) == "2" 或 str(i) == "2"
我该如何解决这个问题并使其正常工作(不将其转换回整数,因为那样会使我的代码有点难看)
您不应使用 ==
比较 String
值。请改用 equals()
函数:
if (r.equals("2")) {
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.)
更多信息在这里:How do I compare strings in Java?