【发布时间】:2014-04-07 00:51:03
【问题描述】:
我写了一个学习arraylists的程序。本质上,它所做的是从字符串数组(每个单词)中提取并使用并行数组列表查找重复项。有两个数组列表,一个用于单词,一个用于每个单词出现的次数。单词列表第 0 位的单词对应计数列表第 0 位的数字,以此类推。我成功地找到了重复的单词并计算了它们的出现次数,但是对于仅在我计数为 2 时才出现的单词,我似乎无法找出原因。这是代码
String[] wordList = fileContents.split("\\s");
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> counts = new ArrayList<Integer>();
words.add(wordList[0]);
counts.add(0);
for (int i = 0; i < wordList.length; i++) {
String tempWord = wordList[i];
boolean foundEqual = false;
int count = 0;
for(int q = 0;q < words.size();q++) {
if (tempWord.equals(words.get(q))) {
foundEqual = true;
counts.add(q, counts.get(q) + 1);
}
}
if(!foundEqual){
words.add(tempWord);
counts.add(1);
}
}
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i) + ":" + counts.get(i));
}
这里是单词
this is a test
this is also a test
this is the last test
这里是输出,你可以看到最后三个项目应该是 1 但是 2。
this:3
is:3
a:2
test:3
also:2
the:2
last:2
任何帮助将不胜感激!
【问题讨论】:
标签: java arrays arraylist histogram