gpt4 book ai didi

java - java客户端中的NullPointer异常?

转载 作者:行者123 更新时间:2023-12-01 07:35:18 24 4
gpt4 key购买 nike

我正在编写一个简单的客户端,但我总是在以下位置收到 NullPointerException:

            while ((input = in.readLine()) != null) {

这是我的代码:

public class ClientTest {

public static String server = "127.0.0.1";
public static int sport = 11111;
public static int cport = 11111;
private static String clientname="";
public static ExecutorService pool = Executors.newCachedThreadPool();
public static BufferedReader in = null;
public static PrintWriter out = null;
public static Socket socket = null;

public ClientTest(){
this.clientname="";
}


public static void main(String[] args) {

try {
socket = new Socket(server, sport);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch(IOException e) {
System.out.println("could not create connection:\n" + e);
try {
if(socket != null) socket.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
pool.execute(new Communicator());

}

public static class Communicator implements Runnable {
@Override
public void run() {
String input = "";
try {
while ((input = in.readLine()) != null) {//here i get the NPException
StringTokenizer tokenizer = new StringTokenizer(input);
tokenizer.nextToken();

if(input.startsWith("!open")) {
if(tokenizer.hasMoreTokens()) System.out.print(tokenizer.nextToken() + "> ");
else System.out.print("> ");
}
else if(input.startsWith("!exit")) {
System.out.print("Hallo hallo");
}
}
} catch(IOException e) {
System.out.println("An error as occurred while reading from server - \n" + e);
}
}

}


}

为什么我会收到NullPointerException?我仍在初始化字符串输入。

最佳答案

My question is, why do I get the NP Exception, I am still initializing the String input!

如果 in 为 null,您将得到一个 NullPointerException ......这当然有可能。毕竟,如果 main 的第一部分中的任何内容抛出异常,您可以捕获它,将其打印出来......然后继续!因此,如果 socket.getOutputStream() 抛出异常,inout 都将为 null。

寓意:捕获异常并像什么都没发生一样继续很少是一个好主意。

关于java - java客户端中的NullPointer异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com