I writing a program learning arraylists. Essentially what it does is pulls from an array of Strings (each a word) and find the duplicates using to parallel arraylists. There are two arraylists one for the words and one for the number of times each word appears. The word in 0th spot of the words list corresponds to the number in the 0th spot of counts list and so on. I am successfully finding duplicate words and counting their occurrences but for words that occur only once I am getting a count of 2 and I can't seem to find out why. Here is the code
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));
}
Here are the words
this is a test
this is also a test
this is the last test
And here it the output, as you can see the last three items should be 1 but are 2.
this:3
is:3
a:2
test:3
also:2
the:2
last:2
Any help would be really appreciated!