处理 loadStrings 字符串总是不同的,即使看似相等
Processing loadStrings strings are always different, even if seemingly equal
在处理过程中,我一直在尝试读取包含不同字符串的文本文件。当使用 saveStrings 函数通过 Processing 读取并进行比较时,它们总是不同的,即使这些行在 get 文件中看起来是相等的。我最近尝试使用 saveStrings 写入文本文件,但这也不起作用。
String lines[] = loadStrings("list.txt");
String list[] = {"1", "1"};
void test() {
saveStrings("data/list.txt", list);
println(lines[0] == lines[1]); //returns false
println("1" == "1"); //returns true
}
我只是调用了设置函数中的方法。
不要使用 ==
来比较 String
值。请改用 equals()
函数:
println(lines[0].equals(lines[1]));
您需要这样做,因为 ==
比较两个 String
值是否是同一个对象。 literal "1"
等于其自身,因此它的计算结果为 true
。但是,您从文件中读入的两个 String
值不是同一个对象,因此 ==
的计算结果为 false
。
equals()
函数实际上检查 String
值和 returns true
中的字符是否包含相同的字符。
the Processing reference中也有介绍:
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.)
在处理过程中,我一直在尝试读取包含不同字符串的文本文件。当使用 saveStrings 函数通过 Processing 读取并进行比较时,它们总是不同的,即使这些行在 get 文件中看起来是相等的。我最近尝试使用 saveStrings 写入文本文件,但这也不起作用。
String lines[] = loadStrings("list.txt");
String list[] = {"1", "1"};
void test() {
saveStrings("data/list.txt", list);
println(lines[0] == lines[1]); //returns false
println("1" == "1"); //returns true
}
我只是调用了设置函数中的方法。
不要使用 ==
来比较 String
值。请改用 equals()
函数:
println(lines[0].equals(lines[1]));
您需要这样做,因为 ==
比较两个 String
值是否是同一个对象。 literal "1"
等于其自身,因此它的计算结果为 true
。但是,您从文件中读入的两个 String
值不是同一个对象,因此 ==
的计算结果为 false
。
equals()
函数实际上检查 String
值和 returns true
中的字符是否包含相同的字符。
the Processing reference中也有介绍:
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.)