我正在尝试创建一个IRC Bot,下面是代码,但是,当它运行时,无论我尝试什么,它都不会检测到“001”,我在JRE6上运行它并使用JDK6。我正在使用Eclipse开发它并使用调试功能来运行它。我试过“java.exe”和“javaw.exe”。在运行时,debugex显示001显然就在那里。
这是我的代码:
package bot;
import java.io.*;
import java.net.*;
public class Main {
static PrintWriter out = null;
@SuppressWarnings("unused")
public static void main(String[] args) {
Socket sock = null;
BufferedReader in = null;
try {
sock = new Socket("irc.jermc.co.cc",6667);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
boolean sentconnect = false;
while(sock.isConnected() == true){
if(sentconnect == false){
writeout("NICK GBot");
writeout("USER GBot GBot GBot :GBot");
sentconnect = true;
}
String data = "";
try {
data = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
data = data.trim();
if(data != ""){
System.out.println("[IN] " + data);
}
String[] ex;
ex = data.split(" ");
for(String debugex : ex){
//System.out.println("DEBUGEX: " + debugex);
}
if(ex[1] == "001"){
writeout("JOIN #minecraft");
}
try {
Thread.sleep((long) 0.5);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ex[0] == "PING"){
writeout("PONG " + ex[1]);
}
}
}
private static void writeout(String msg) {
out.println(msg);
System.out.println("[OUT] " + msg);
}
}
答案 0 :(得分:2)
必须使用String.equals()
而不是==
来测试字符串相等性。
应该是:
if(! data.isEmpty()){ // rather than: data != ""
System.out.println("[IN] " + data);
}
...
if(ex[1].equals("001")){ // rather than: ex[1] == "001"
writeout("JOIN #minecraft");
}
...
if(ex[0].equals("PING")){ // rather than: ex[0] == "PING"
writeout("PONG " + ex[1]);
}