我的任务即将结束,我被指示要做的最后一件事是:
- 使用 keySet() 检索键集(映射的字符串部分)。循环这个集合并打印出单词及其计数。
我已经使用 keySet() 方法打印出 HashMap 中的键数,但我还没有做的是找到 HashMap 中每个单词的长度,然后打印出每个单词中的字符数。我目前不确定我应该如何做到这一点。我假设我会使用一些时间的 for 循环来遍历我已经完成的 keySet(),然后使用类似 .length() 的方法来找出每个单词的长度,然后以某种方式打印出来?
到目前为止,这是我的相关代码:
主班
package QuestionEditor;
import java.util.Set;
public class Main{
public static void main (String[] args) {
WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");
Set<String> set = secondWordGroup.getWordCountsMap().keySet();
System.out.println("set : " + set + "\n");
for(String key : set)
{
System.out.println(key);
}
}
}
WodGroup 类
package QuestionEditor;
import java.util.HashMap;
public class WordGroup {
String word;
// Creates constructor which stores a string value in variable "word" and converts this into lower case using
// the lower case method.
public WordGroup(String aString) {
this.word = aString.toLowerCase();
}
public String[] getWordArray() {
String[] wordArray = word.split("-");
return wordArray;
}
public HashMap<String, Integer> getWordCountsMap() {
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
for (String word : this.getWordArray()) {
if (myHashMap.keySet().contains(word)) {
myHashMap.put(word, myHashMap.get(word) + 1);
} else {
myHashMap.put(word, 1);
}
}
return myHashMap;
}
}
任何有关如何做到这一点的帮助将不胜感激,谢谢。
更新 所以当我的代码编译时,我得到了输出:
Key: play has 3 counter
Key: all has 1 counter
Key: at has 1 counter
Key: work has 1 counter
Key: hard has 1 counter
Key: when has 2 counter
Key: you has 2 counter
Key: dont has 1 counter
但我真正想做的是打印出每个单词中的字符数量。因此,例如,play 将计算 4 次,all 将计算 3 次,at 将计算 2 次等。关于如何实现这一点的任何想法?