编辑:我只是将TreeMap更改为HashMap,现在它可以正常工作了,但仍然无法满足我的需要。
嘿,这是我坚持了很长时间的事情。
我的目标是从文件中获取文本sequence.txt
,然后调用传递扫描器s
和整数的构造函数n
。在构造函数内部,我的目标是n
从sequence
ArrayList中读取单词并将其保存,然后内部映射应该能够紧接单词序列后立即n
提取单词,并计数n + thisWord存在的次数。
因此,一个示例将是这n个(或5个)单词:
so an to me for
然后第六个可能是and
,因此在原始地图中它将是:
map.put(arrList,innerMap);
其中arrList将被包含so, an, to, me, for
,而innerMap看起来像这样and | 1
然后从那里开始,每增加一个新对象,对于相同的序列,它将使整数增加一。我会担心第二部分,但是我什至无法使我的代码正常工作,而且我不知道自己做错了什么。这是我的构造函数:
public RandomWriter(Scanner s, int n) {
Map<String, Integer> valMap = new HashMap<String, Integer>();
this.s = s;
this.n = n;
map = new HashMap<>(); `
Queue<String> tmp = new LinkedList<String>();
for (int i = 0; i < n; i++) {
tmp.add(s.next());
}
while (s.hasNext()) {
ArrayList<String> tmpList = new ArrayList<String>();
tmpList.addAll(tmp);
String current = s.next();
if (!valMap.containsKey(current)) {
valMap.put(current, 1);
} else {
valMap.put(current, valMap.get(current + 1));
}
tmp.add(current);
tmp.remove();
map.put(tmpList, valMap);
}
// s.next();
System.out.println(map.keySet());
}
更改为HashMap后,它现在如下打印:
[[today, day], [me, and], [so, if], [in, for], [for, you], [top, in], [sent, receive], [for, many], [on, top], [or, on], [do, do], [side, so], [so, when], [under, on], [many, much], [to, do], [row, on], [for, when], [when, become], [dog, house], [toy, your], [many, is], [won, do], [become, inside], [why, to], [to, spell], [me, you], [school, under], [too, your], [hit, high], [can, do], [is, to], [for, how], [receive, get], [on, me], [animal, your], [to, animal], [inside, to], [your, for], [cat, many], [who, me], [spell, word], [do, cat], [house, live], [how, can], [your, who], [word, sent], [to, today], [canvas, word], [on, for], [low, ball], [which, many], [animal, if], [much, mouse], [live, living], [your, sent], [if, how], [high, kill], [ball, hit], [if, so], [in, side], [get, which], [you, if], [so, for], [do, if], [get, toy], [so, row], [if, to], [to, if], [win, won], [how, when], [inside, in], [dog, squirrel], [you, to], [and, you], [so, or], [word, school], [mouse, for], [for, why], [day, dog], [squirrel, fish], [your, if], [cat, dog], [for, which], [to, when], [more, for], [to, your], [which, cat], [living, canvas], [kill, win], [you, low], [when, inside], [fish, animal], [do, so], [many, more], [to, too], [when, to]]
这是它正在进入的地图:
private Map<ArrayList<String>, Map<String, Integer>> map;
这是错误的:
if (!valMap.containsKey(current)) {
valMap.put(current, 1);
} else {
valMap.put(current, valMap.get(current + 1));
}
您可能想要:
if (!valMap.containsKey(current)) {
valMap.put(current, 1);
} else {
valMap.put(current, valMap.get(current) + 1);
}
由于如果映射包含key current
,那么您要添加1
到该key的值,而不要用key的值覆盖它,current+1
甚至可能不存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句