java - How do I get the value of a variable from another method without passing it off as an argument?
问题描述
I'm trying to create a chatting application (yes I know, not very creative) and I want to transfer the socket variable's value into the other method.
But I'm too confused as to what should I do?
I've already tried passing it off as an argument which for some reason doesn't work, also tried to declare the variables outside of the method which also doesn't work.
public void DeclaringVariables() throws IOException{
InetAddress group = InetAddress.getByName("239.255.255.255");
int port = 1201;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
name = sc.nextLine();
MulticastSocket socket = new MulticastSocket(port);
// Since we are deploying
socket.setTimeToLive(0);
//this on localhost only (For a subnet set it as 1)
socket.joinGroup(group);
Thread t = new Thread(new
ReadThread(socket,group,port));
// Spawn a thread for reading messages
t.start();
}
/**
*
*/
public void SendButton() {
try {
while(true) {
String message;
message = sc.nextLine();
if(message.equalsIgnoreCase(GroupChat.TERMINATE))
{
finished = true;
socket.leaveGroup(group);
socket.close();
break;
}
message = name + ": " + message;
byte[] buffer = message.getBytes();
DatagramPacket datagram = new
DatagramPacket(buffer,buffer.length,group,port);
socket.send(datagram);
}
}
catch (IOException ex) {
Logger.getLogger(ChatGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
解决方案
如果您需要socket
多个方法,请考虑将其声明为类属性,而不是局部变量。这样,您可以在类构造函数中实例化它并通过类中的所有方法访问它。像这样:
public class MyClass {
// declare it here
private MulticastSocket socket;
public MyClass() {
// instantiate it here
socket = new MulticastSocket(1201);
}
public void myMethod() {
// now you can use it everywhere!
socket.someMethod();
}
}
推荐阅读
- android - 如何指定要从中访问数据的文档?
- python - 让 Keras / Tensorflow 输出 OneHotCategorical,但操作没有梯度
- reactjs - 如何为生产配置 React 应用程序
- javascript - 单击按钮时HTML函数不返回值
- python - 如何识别带有彩色背景图像的文本?
- java - JPA 与 PostgreSQL - 简单的关系
- python - 使用随机函数(Python 乌龟图形)
- javascript - 如何更改 Material-UI 滑块颜色
- c# - 从标签助手中,我如何访问不是标签助手属性的属性?
- sql-server - 我在尝试更正 sql server 2016 中的转换问题时遇到问题