我在 mac 上使用 eclipse IDE(版本:3.4.2)时遇到了以下问题。
当使用 equal() 或 equalsIgnoreCase() 方法比较字符串时,即使字符串相等,我也会收到 false。例如,下面的代码将以下条件视为假,即使 values[0] = "debug_mode"
if (values[0].equalsIgnoreCase("debug_mode"))
debug_mode = true;
这是以下循环的一部分:
String value = dis.readLine();
String values[] = value.trim().split("=");
if (values.length >= 2)
{
Config.prnt_dbg_msg(values[0] + "\t" + values[1]);
if (values[0].equalsIgnoreCase("debug_mode"))
debug_mode = isTrue(values[1]);
if (values[0].equalsIgnoreCase("debug_query_parsing"))
debug_query_parsing = isTrue(values[1]);
if (values[0].equalsIgnoreCase("username"))
Connection_Manager.alterAccessParameters(values[1], null, null);
if (values[0].equalsIgnoreCase("password"))
Connection_Manager.alterAccessParameters(null, values[1], null);
if (values[0].equalsIgnoreCase("database"))
Connection_Manager.alterAccessParameters(null, null, values[1]);
if (values[0].equalsIgnoreCase("allow_duplicate_entries"))
allow_duplicate_entries = isTrue(values[1]);
}
我尝试使用 value[0].equal("debug_mode")
并得到相同的结果。
有人知道为什么吗?
最佳答案
那确实很奇怪 :) 你能把上面的代码改成这样吗:
if ("debug_mode".equalsIgnoreCase("debug_mode"))
debug_mode = true;
确认它工作正常,然后仔细检查为什么您的 values[0]
不是“debug_mode”。
以下是我现在想到的要检查的事项列表:
- 检查
values[0].length() == "debug_mode".length()
- 我非常怀疑,但无论如何让我把它放在桌面上 - 你有没有机会使用 Unicode?li>
- 你能打印每个字符并在该字符和“debug_mode”字符串的相应字符之间执行
.equals()
吗? - 如果这是在一个更大的项目中,你能在一个简单的 Java 项目中做同样的事情并确认它在那里工作吗?
澄清一下,问题实际上是在使用 DataInputStream.readLine
。来自 javadoc(http://download.oracle.com/javase/1.6.0/docs/api/java/io/DataInputStream.html):
readLine()
Deprecated. This method does not properly convert bytes to characters. ...
它实际上以一种微妙的方式与 Unicode 相关 - 当您执行 writeChar
时,您实际上写入了两个字节 0
和 97
,大-endian 字母 a
的 Unicode。
这是一个显示行为的独立片段:
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws Exception {
String os = "abc";
System.out.println("---- unicode, big-endian");
for(byte b: os.getBytes("UTF-16BE")) {
System.out.println(b);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for(char c: os.toCharArray()) {
dos.writeChar(c);
}
byte[] ba = baos.toByteArray();
System.out.println("---- ba");
for(byte b: ba) {
System.out.println(b);
}
ByteArrayInputStream bais = new ByteArrayInputStream(ba);
DataInputStream dis = new DataInputStream(bais);
System.out.println("---- dis");
String s = dis.readLine();
System.out.println(s);
System.out.println("String length is " + s.length()
+ ", but you would expect " + os.length()
+ ", as that is what you see printed...");
}
}
故事的寓意 - 不要使用已弃用的 api...另外,空格是无声的 killer :http://www.codinghorror.com/blog/2009/11/whitespace-the-silent-killer.html
关于java - equal() 和 equalsIgnoreCase() 对相等的字符串返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210713/