首页 > 解决方案 > 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);
    }
    }

标签: javavariablesinheritance

解决方案


如果您需要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();
    }

}

推荐阅读