PaperTronics
PaperTronics

Reputation: 3

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

Upvotes: 0

Views: 55

Answers (1)

Óscar López
Óscar López

Reputation: 236004

If you need socket in more than one method, consider declaring it as a class attribute, instead of a local variable. In that way you can instantiate it in the class constructor and access it through all the methods in the class. Like this:

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

}

Upvotes: 3

Related Questions