2015-06-16 31 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