如果带有字符串比较的语句失败 [英] If statement with String comparison fails

查看:34
本文介绍了如果带有字符串比较的语句失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道为什么下面的 if 语句没有执行:

I really don't know why the if statement below is not executing:

if (s == "/quit")
{
    System.out.println("quitted");
}

以下是全班.

这可能是一个非常愚蠢的逻辑问题,但我一直在这里无法弄清楚这一点.

It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.

感谢您的关注:)

class TextParser extends Thread {
    public void run() {
        while (true) {
            for(int i = 0; i < connectionList.size(); i++) {
                try {               
                    System.out.println("reading " + i);
                    Connection c = connectionList.elementAt(i); 
                    Thread.sleep(200);

                    System.out.println("reading " + i);

                    String s = "";

                    if (c.in.ready() == true) {
                        s = c.in.readLine();
                        //System.out.println(i + "> "+ s);

                        if (s == "/quit") {
                            System.out.println("quitted");
                        }

                        if(! s.equals("")) {
                            for(int j = 0; j < connectionList.size(); j++) {
                                Connection c2 = connectionList.elementAt(j);
                                c2.out.println(s);
                            }
                        }
                    }
                } catch(Exception e){
                    System.out.println("reading error");
                }
            }
        }
    }
}

推荐答案

在您的示例中,您比较的是字符串对象,而不是它们的内容.

In your example you are comparing the string objects, not their content.

你的比较应该是:

if (s.equals("/quit"))

或者如果 s 字符串无效性不介意/或者你真的不喜欢 NPE:

Or if s string nullity doesn't mind / or you really don't like NPEs:

if ("/quit".equals(s))

这篇关于如果带有字符串比较的语句失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆