本质上,我试图获取我已经添加到数组列表中的单词的单词计数
(使用addWord方法)。起初我尝试使用流,但是我放弃了,现在我试图使用相对简单的迭代器方法。我只是无法使其工作(我总是得到0)。任何帮助,将不胜感激
主要方法
import java.util.List;
/**
* A simple 'driver' for the WordAnalyser class.
*
* Split a 'document' into individual words and pass them
* to a WordAnalyser to be analysed.
*
* In this example, the 'document' is a String literal in
* the main method, but this could easily be changed to an
* external file, if desired (e.g., use a Scanner).
*
* Print a few sample statistics.
*
*/
public class WordAnalyserMain
{
public static void main(String[] args)
{
String document =
"The first day of the third month was always difficult for Joy because there was little to look forward to in the month of March.";
String[] words = document.split("[ ,.;:?]+");
WordAnalyser analyser = new WordAnalyser();
for(String word : words) {
analyser.addWord(word);
}
for(String word : List.of("The", "the", "joy", "was")) {
System.out.println(word);
System.out.println(" " + analyser.getCount(word));
System.out.println(" " + analyser.getCaseInsensitiveCount(word));
System.out.println(" " + analyser.followedBy(word, "month"));
}
}
}
到目前为止我的wordAnalyser类
import java.util.*;
/**
* Keep track of word counts and word pairs.
*
* @author
* @version
*/
public class WordAnalyser
{
private HashMap<String,Integer> counts;
private ArrayList<String> WordAnalyser;
private String wordCounts;
private String Sentences;
private int count;
private Map<String, Integer> wordCount = new HashMap<String, Integer>();
/**
* Constructor for objects of class WordAnalyser
*/
public WordAnalyser()
{
counts = new HashMap<>();
WordAnalyser = new ArrayList<>();
}
/**
* Uses a for each loop to add the input, starting from 0
*/
public void addWord(String input)
{
WordAnalyser.add(input);
this.counts = counts;
for (String word : WordAnalyser)
{
int counter = counts.getOrDefault(word , 0);
counts.put(word,counter +1);
System.out.println(input);
}
}
/**
* Get the number of times the given word has been seen.
* @param word The word to be looked up.
* @return The number of times the word has been seen.
*/
public int getCount(String word)
{
Map<String, Integer> wordCount = new HashMap<String, Integer>();
this.count=count;
for(String words: WordAnalyser) {
Integer count = wordCount.get(words);
wordCount.put(words, (count== null) ? 1 : count+1);
}
return count;
}
}
最佳答案
如果我正确理解您的意见:
private Map<String, Integer> save;
public void addWord(String word) {
if(save.containsKey(word)) {
save.put(word, save.get(word)+1);
} else {
save.put(word, 1);
}
}
public int getCount(String word) {
return save.containsKey(word) ? save.get(word) : 0;
}
关于java - 无法设法获得字数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59707295/