简体   繁体   中英

Java chat room program

I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.

Client.java

public class Client {
    Server.names();
}

Server.java

public class Server {    
    public static HashSet<String> names = new HashSet<String>();

    public static void main(String[] args) throws Exception{                    
        while(true){
            name = in.readLine();
            if(name == null){
                return;
            }
            if(!names.contains(name)){
                 names.add(name);
                 break;
            }            
        }
    }
}

Your Q is a bit unclear, but if you want to get the HashSet , names from your Server class, you need to get the reference to it by calling Server.name , not Server.name() as it is not a method.

Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names . In this case you can call the main method of Server (see this related Q here ) but unless you really want that to be your main method of Server , I would recommend renaming the method to populateNames() or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM