Java 在我的代码中不断遇到类变量问题
我正在玩一点Java,开始用Java代码为一个基于聊天的小应用程序创建一个客户端。我试图使变量Java 在我的代码中不断遇到类变量问题,java,variables,Java,Variables,我正在玩一点Java,开始用Java代码为一个基于聊天的小应用程序创建一个客户端。我试图使变量ssocket成为一个类变量,它将是连接服务器的变量(尚未编写,但这不是问题所在)。因此,我在类声明的正下方声明类变量ssocket,然后(我一直这样做并注释掉)将ssocket声明为构造函数中的空套接字。然后,在一个名为sendToSever的方法中,我尝试引用它来设置主机、端口和内容,但它一直说它应该是一个局部变量,而不是类变量。但是,几行之后,用同样的方法,我引用了它。另外,当我尝试在try块中将
ssocket
成为一个类变量,它将是连接服务器的变量(尚未编写,但这不是问题所在)。因此,我在类声明的正下方声明类变量ssocket
,然后(我一直这样做并注释掉)将ssocket
声明为构造函数中的空套接字。然后,在一个名为sendToSever
的方法中,我尝试引用它来设置主机、端口和内容,但它一直说它应该是一个局部变量,而不是类变量。但是,几行之后,用同样的方法,我引用了它。另外,当我尝试在try
块中将ssocket
设置为构造函数中的主机和端口时,它也没有使用class变量。我想在sendToSever
中正式设置套接字,以便他们每次执行操作时都可以尝试重新连接,但我不知道如何解决此问题。如果有什么不清楚的地方,我很乐意编辑这篇文章
我试过:
您的错误是未关闭构造函数方法:
public ClientGUI() throws IOException {
ssocket = new Socket();
// } should be closed her, but was not
public int sendToServer(String text) {
...
}
我注意到代码中的一些问题,并做了以下更改
// static variable, single reference is shared across all instances of the class
private static Socket ssocket = null;
public ClientGUI() throws IOException {
// ssocket is not initialized here
}
public int sendToServer(String text) {
try (
if (ssocket == null) {
// typo, socket is used in code instead of ssocket
ssocket = new Socket("127.0.0.1", 123456);
}
// ...
} catch (Exception e) {
// if connectivity issue occurred, you can close the ssocket and set to null here
// ...
}
}
希望这有帮助。不要再链接到您的代码。相反,请修复格式错误,以便正确地包含它。我已经编辑了您的问题,将您的代码包含在Pastebin中。在您的构造函数之后,您缺少一个右大括号
}
。凯,谢谢,我现在就去试试这个。我可能错过了}
,因为我复制粘贴不好(不想复制整个程序,因为它有200多行)。@neurophicker我也认为丢失的}是复制粘贴问题,不管怎么说。希望这些说明能推动你前进。好吧,看起来它奏效了;我不得不去掉括号,但是Java一直说它需要大括号;如果是这样的话,那会导致更多的错误。
// static variable, single reference is shared across all instances of the class
private static Socket ssocket = null;
public ClientGUI() throws IOException {
// ssocket is not initialized here
}
public int sendToServer(String text) {
try (
if (ssocket == null) {
// typo, socket is used in code instead of ssocket
ssocket = new Socket("127.0.0.1", 123456);
}
// ...
} catch (Exception e) {
// if connectivity issue occurred, you can close the ssocket and set to null here
// ...
}
}