2015-06-16 32 views
0

因此,我正在制作一个IRC机器人,我希望能够创建一个系统供用户使用“!note”输入笔记,稍后使用“!提醒”提醒。为IRC机器人创建一个笔记系统

我不得不想法让一个HashMap,使用此代码:

public HashMap notes = new HashMap(); 

if (message.startsWith("!note ")) { 
    notes.put(sender.toLowerCase(), message.substring(6)); 
    sendMessage(channel, "Note recorded."); 
} 
if (message.startsWith("!remind ")) { 
    String nick = message.substring(8); 
    String remind = (String) notes.get(nick.toLowerCase()); 
    sendMessage(channel, remind); 
} 

但是,这将只允许每个用户一个音符,因为一个HashMap中没有重复。

有什么更好的让用户存储多个笔记?

+0

为什么不'的HashMap <字符串,列表>'? –

+0

Multimap听起来很合理http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html – Shaun

+0

@ug_用户一次只能添加一个项目,所以这就是为什么我有'HashMap '。如果我试图将其更改为'HashMap >',那么我得到的错误字符串不能转换为列表。有没有办法解决这个问题?对不起,因为我是Java新手。 – quibblify

回答

0

您可以简单地存储字符串列表而不是单个字符串。

public HashMap<String, List<String>> userNotesStore = new HashMap<String, List<String>>(); 

/** 
* Adds a note to the users list of notes. 
* @param username 
* @param note 
*/ 
private void addNote(String username, String note) { 
    List<String> notes = userNotesStore.get(username); 
    if(notes == null) { 
     notes = new ArrayList<String>(); 
     userNotesStore.put(username, notes); 
    } 
    notes.add(note); 
} 

然后使用您现有的代码,你可以修改它是这样

if (message.startsWith("!note ")) { 
    addNote(sender.toLowerCase(), message.substring(6)); 
    sendMessage(channel, "Note recorded."); 
} 
if (message.startsWith("!remind ")) { 
    String nick = message.substring(8); 
    List<String> notes = userNotesStore.get(nick); 
    if(notes != null) { 
     // send all notes to the user. 
     for(String note : notes) { 
      sendMessage(channel, note); 
     } 
    } else { 
     // send no notes message? 
     sendMessage(channel, "*You have no notes recorded."); 
    } 
} 
+0

谢谢!我现在知道了。 – quibblify