java - 为什么两个相等的字符串不匹配?

标签 java c# android string if-statement

我想将来自服务器的响应字符串进行比较,但在测试这两个字符串时我得到了错误的结果。为什么?

我找到了这个但没有帮助:How do I compare strings in Java?

我尝试了两种方式:

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
String code;
if(Objects.equals((code = in.readLine()), "S")) { //Input string: "S"
    //code
}

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
String code;
if((code = in.readLine()).equals("S")) { //Input string: "S"
    //code
}

代码在任何一种情况下都不会运行,因为测试的值为 false

完整代码

服务器端 - C# (Windows)

class ManagePhoneClients
    {
        public void managePhoneClients(object obj)
        {
            Boolean socketalive = true;
            TcpClient tcpClient = (TcpClient)obj;
            StreamReader sr = new StreamReader(tcpClient.GetStream(), Encoding.UTF8);
            StreamWriter sw = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
            Boolean isPhoneClientConnected = false;
            String user;
            String answer;
            String tl;
            List<string> LC = new List<string>();
            Boolean qss = false;
            Program program = new Program();
            Int32 points = 0;

            ConsoleMethods.writeLine("Thread started for the phone client.", "Info", ConsoleColor.Cyan);

            sw.WriteLine("S");
            sw.Flush();

            while (socketalive == true)
            {
                try
                {
                    if (Program.isMainClientConnected != true || Program.isPowerPointConnected != true)
                    {
                        ConsoleMethods.writeLine("Connection refused because the necessary clients are not connected!", "Error", ConsoleColor.Red);
                        sw.WriteLine("NS");
                        sw.Flush();
                        tcpClient.Close();
                        socketalive = false;
                    }
                    else
                    {
                        sw.WriteLine("LC");
                        sw.Flush();
                    }
                    if (isPhoneClientConnected != true & sr.Peek() != -1)
                    {
                        String rLC = sr.ReadLine();
                        LC.AddRange(rLC.Split('|'));
                        if (LC[1].ToString() == Program.passPhoneClient)
                        {
                            user = LC[0];
                            Program.userNames.Add(user);
                            ConsoleMethods.writeLine("Phone connected from: " + tcpClient.Client.RemoteEndPoint, "Info", ConsoleColor.Cyan);
                            sw.WriteLine("S");
                            sw.Flush();
                            Program.utnr = rLC;
                            isPhoneClientConnected = true;
                        }
                        else
                        {
                            sw.WriteLine("NS");
                            sw.Flush();
                            socketalive = false;
                            ConsoleMethods.writeLine("Phone client disconnected because the password was invalid!", "Error", ConsoleColor.Red);
                        }

                    }
                    switch (sr.ReadLine())
                    {
                        case "CLIENT-EXCEPTION":
                            ConsoleMethods.writeLine("Exception in phone client from: " + tcpClient.Client.RemoteEndPoint + "\n" + sr.ReadLine(), "Client-Error", ConsoleColor.DarkRed);
                            break;
                        case "RECEIVED_POINTS":
                            int point = int.Parse(sr.ReadLine());
                            points += point;
                            ConsoleMethods.writeLine("Phone client succesfully completed a task from: " + tcpClient.Client.RemoteEndPoint + " Point: " + point, "Client-Received Points", ConsoleColor.DarkRed);
                            ConsoleMethods.writeLine("Phone client collected points from: " + tcpClient.Client.RemoteEndPoint + " Points: " + points, "Client-Collected Points", ConsoleColor.DarkRed);
                            break;
                    }

                }
                catch (Exception e)
                {
                    tcpClient.Close();
                    socketalive = false;
                    ConsoleMethods.writeLine(e.Message + e.StackTrace + e.StackTrace, "Error", ConsoleColor.Red);
                }
            }
        }
    }

(这还没有完成!)

客户端 - Java (Android)

   public void login(View v) {
        final Context context = this;
        new Thread(new Runnable() {
            public void run() {
                try {
                    final Socket socket = new Socket("192.168.0.104", 90);
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    out.print("P" + "\r\n");
                    out.flush();
                    String code;
                    code = in.readLine();
                    if(code.equals("S")) {
                        if (Objects.equals((code = in.readLine()), "LC")) {
                            out.print(((EditText)findViewById(R.id.username)).getText().toString() + "|" + ((EditText)findViewById(R.id.password)).getText().toString() + "\r\n");
                            out.flush();
                            if(Objects.equals((code = in.readLine()), "S")) {
                                new ServerContact(context).Listener(socket);
                                startActivity(new Intent(Login.this, Waiting.class));
                            } else {
                                throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
                            }
                        } else {
                            throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
                        }
                    } else {
                        throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
                    }
                } catch (Exception e) {
                    new ExceptionWriter(e);
                }
            }
        }).start();
    }

(这还没有完成!)

最佳答案

我设法解决了它。在服务器端,我必须禁用 BOM。

无 BOM:

StreamWriter sw = new StreamWriter(tcpClient.GetStream(), new UTF8Encoding(false));

有 BOM:

StreamWriter sw = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);

关于java - 为什么两个相等的字符串不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710530/

相关文章:

Java:如何使用具有多个类的持卡人

java - 使用特殊构造函数 java 创建类

c# - 使用校验和进行文件比较

c# - RestSharp 不在 .NET Core 2.0 中使用代理(Fiddler)

android - CameraRoll 不显示 Android 上的图像

java - 如何拟合 hdodenhof 圆 imageview

java - 如何在 actionPerfomed() 中调用 actionPerformed()

c# - 配置文件与注册表,用于在 C# .net 中保存可配置值

android - 按下后退按钮时Android崩溃

java - 如何在服务器页面中复制文件而不读取