MBy*_*ByD 13 java string string-comparison
我在mac上使用eclipse IDE(版本:3.4.2),我遇到了以下问题.
当使用equal()或equalsIgnoreCase()方法比较字符串时,即使字符串相等,我也会收到false.例如,下面的代码将以下条件视为false,即使值[0] ="debug_mode"
if (values[0].equalsIgnoreCase("debug_mode"))
debug_mode = true;
Run Code Online (Sandbox Code Playgroud)
这是以下循环的一部分:
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]);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用value[0].equal("debug_mode")
并得到了相同的结果.有人知道为什么吗?
icy*_*com 22
这确实很奇怪:)你可以将上面的代码更改为:
if ("debug_mode".equalsIgnoreCase("debug_mode"))
debug_mode = true;
Run Code Online (Sandbox Code Playgroud)
确认它工作正常,然后仔细检查为什么你values[0]
不是"debug_mode".
以下是我现在想到的一个要检查的事项清单:
values[0].length() == "debug_mode".length()
.equals()
在该字符和"debug_mode"字符串的相应字符之间进行操作吗?澄清一下,问题实际上是在使用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. ...
Run Code Online (Sandbox Code Playgroud)
它实际上与一个微妙的方式有关 - 当你这样做时,writeChar
你实际上写了两个字节,0
并97
为字母写了big-endian Unicode a
.
这是一个显示行为的自包含代码段:
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...");
}
}
Run Code Online (Sandbox Code Playgroud)
故事的道德 - 不要使用弃用的api ...而且,空白是无声的杀手:http://www.codinghorror.com/blog/2009/11/whitespace-the-silent-killer.html
小智 7
我使用equalsIgnoreCase刚刚遇到了同样的问题.
几个小时的盯着屏幕,调试我明白我的if语句有的代码; 在末尾,
即
if ("stupid".equalsIgnoreCase.("STupid");
{
//it always gets here
}
Run Code Online (Sandbox Code Playgroud)
希望这有助于将来的某些人.