简体   繁体   English

Java聊天室程序

[英]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. 我必须在gui中显示当前用户,但一直说该哈希集为空,这困扰了我好几个小时。 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 Client.java

public class Client {
    Server.names();
}

Server.java 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. 您的Q有点不清楚,但是如果要从Server类获取HashSet names ,则需要通过调用Server.name而不是Server.name()来获取对它的引用,因为它不是方法。

Now names will be empty until you populate it. 现在, names将为空,直到您填充它为止。 To populate it you need to call code that will read user input and store it in names . 要填充它,您需要调用将读取用户输入并将其存储在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. 在这种情况下,您可以调用Servermain方法(请参阅此处的相关Q),但是除非您真的希望将其用作Servermain方法,否则我建议将方法重命名为populateNames()或类似名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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