Arrays.equals()和String.equals()始终返回false

时间:2014-07-01 03:00:22

标签: java client-server

这是一个非常令人困惑的问题,我在使用类Array和String中的equals()方法时遇到这些问题:方法总是返回false。我测试了空白,调试了几个小时,我找不到一个修复程序。这是一个加密的服务器聊天室。我只会发布服务器的片段,因为我猜这将是唯一的问题,但如果你想让我发布其他代码或类的片段,我会。 服务器代码段:

private void handlePassword() {
            try {
                out.println(encrypter.encrypted("Enter Password."));
                out.flush();
                char[] ep = null;
                ep = encrypter.decrypted(in.readLine()).toCharArray();
                boolean tr = true;
                if (ep.length == password.length)
                    for (int i = 0; i < ep.length; i++) {
                        System.out.print(ep[i]);
                        System.out.print(password[i]);
                        if (ep[i] == password[i]) {
                            tr = false;
                            break;
                        }
                        System.out.println();
                    }
                System.out.println("AHHHHHHHHHHHH! " + tr);
                System.out.println(String.valueOf(ep) + "\\/"
                        + String.valueOf(password));
                System.out.println(Arrays.equals(ep, password));
                if (!Arrays.equals(ep, password)) {
                    out.println(encrypter.encrypted("Incorrect Password."));
                    out.flush();
                    handlePassword();
                } else {
                    out.println(encrypter.encrypted("Access Granted"));
                    out.flush();
                }
            } catch (Exception e) {
                reportError(e);
            }
        }

- 可变澄清

out = PrintWriter
in = BufferedReader
encrypter = My Encrypting Class
char[] password = The Server Password

- 控制台输出

无效时(密码:asdf)(尝试密码:hhhh):

AHHHHHHHHHHHH! true
[asdf] hhhh\/asdf
false

有效时:(密码:asdf)(尝试密码:asdf):

AHHHHHHHHHHHH! true
[asdf] asdf\/asdf
false

我真的看不出一个问题。请解释为什么会这样。我实在说不出来。

1 个答案:

答案 0 :(得分:1)

从你的输出

AHHHHHHHHHHHH! true [asdf] asdf\/asdf false

ep =“[asdf] asdf”和password =“asdf”,而Arrays.equals(ep,password)在这种情况下返回

我知道,这段代码无效:

if (ep.length == password.length) for (int i = 0; i < ep.length; i++) { System.out.print(ep[i]); System.out.print(password[i]); if (ep[i] == password[i]) { tr = false; break; } System.out.println(); }

也许这行代码

encrypter.decrypted(in.readLine()).toCharArray();

不返回“asdf”?