2017-05-14 25 views
2

我對Java很陌生,正在創建一個軟件應用程序,該應用程序允許用戶將文本輸入到字段中,並且程序將遍歷所有文本並確定最常見的詞是什麼。此刻,我的代碼看起來是這樣的:找到用戶輸入中最常用的詞

JButton btnMostFrequentWord = new JButton("Most Frequent Word"); 
btnMostFrequentWord.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    String text = textArea.getText(); 
    String[] words = text.split("\\s+"); 
    HashMap<String, Integer> occurrences = new HashMap<String, Integer>(); 
    for (String word : words) { 
     int value = 0; 
     if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
     } 
     occurrences.put(word, value + 1); 
    } 

    JOptionPane.showMessageDialog(null, "Most Frequent Word: " + occurrences.values()); 
    } 
} 

這只是打印什麼的話的值,但我想它告訴我的頭號最常用的詞是什麼吧。任何幫助將非常感激。

回答

1
只要你 for循環後

,您可以通過值映射進行排序,然後按值反向排序項,並選擇第一。

for (String word: words) { 
    int value = 0; 
    if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 
} 

Map.Entry<String,Integer> tempResult = occurrences.entrySet().stream() 
       .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) 
       .findFirst().get(); 
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + tempResult.getKey()); 
0

您可以通過事件迭代地圖,找到最大或 嘗試像下面

String text = textArea.getText();; 
String[] words = text.split("\\s+"); 
HashMap<String, Integer> occurrences = new HashMap<>(); 
int mostFreq = -1; 
String mostFreqWord = null; 

for (String word : words) { 
    int value = 0; 
    if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 

    if (value > mostFreq) { 
     mostFreq = value; 
     mostFreqWord = word; 
    } 
} 

JOptionPane.showMessageDialog(null, "Most Frequent Word: " + mostFreqWord); 
0

我會做這樣的事情

int max = 0; 
String a = null; 
for (String word : words) { 
    int value = 0; 
    if(occurrences.containsKey(word)){ 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 
    if(max < value+1){ 
     max = value+1; 
     a = word; 
    } 
} 
System.out.println(a); 

你可以對它進行排序,而解決辦法是要短得多,但是我覺得這個運行速度更快。

0

對於任何人誰是更熟悉Java,這裏是一個非常簡單的方法與Java 8做到這一點:

List<String> words = Arrays.asList(text.split("\\s+")); 

Collections.sort(words, Comparator.comparingInt(word -> { 
    return Collections.frequency(words, word); 
}).reversed()); 

最常見的字存儲在words.get(0)排序後。

相關問題