我正在尝试创建一个"信使"对于一个不和谐的Java机器人。我正在做这个项目来帮助我学习java。我正在初始化连接到事件侦听器的公共方法中的哈希表。我不想每次有事件发生时都重置它。这是我当前的代码:
public class botListeners extends ListenerAdapter {
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
super.onMessageReceived(event);
// ISSUE HERE
Hashtable<String, Integer> messangerDict = new Hashtable<String, Integer>();
if (!event.getAuthor().isBot()) {
String message = event.getMessage().getContentRaw();
System.out.println("A message has been sent: " + message);
String messenger = event.getAuthor().getAsTag();
if (messangerDict.containsKey(event.getAuthor().getAsTag())){
messangerDict.put(messenger, messangerDict.get(messenger) + 1);
}else {
messangerDict.put(event.getAuthor().getAsTag(), 1);
}
System.out.println(messangerDict.toString());
}
}
}
我的当前输出,每次我向"公会"写一条消息时是这样的:
A message has been sent: as
{USERTAG=1}
A message has been sent: s
{USERTAG=1}
我希望它每次递增,即第二次应该是2,而不是1。
每次方法执行时都创建一个新的HashTable
,因此每次方法退出时,您的HashTable
就消失了。将其创建为类的一个字段,如下所示:
public class botListeners extends ListenerAdapter {
Hashtable<String, Integer> messangerDict = new Hashtable<String, Integer>();
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
super.onMessageReceived(event);
if (!event.getAuthor().isBot()) {
// ...