本文介绍了如果带有String比较的语句失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的不知道为什么下面的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
字符串nullity不介意/或者你真的不喜欢NPE:
Or if s
string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
这篇关于如果带有String比较的语句失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!