0

我正在尝试创建一个 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);
    }
}
4

1 回答 1

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]);
        }

请参阅如何比较 Java 中的字符串

于 2012-05-17T22:41:34.793 回答