I just had a homework assignment that wanted me to add all the Java keywords to a HashSet. Then read in a .java file, and count how many times any keyword appeared in the .java file.
The route I took was: Created an String[] array that contained all the keywords. Created a HashSet, and used Collections.addAll to add the array to the HashSet. Then as I iterated through the text file I would check it by HashSet.contains(currentWordFromFile);
Someone recommended using a HashTable to do this. Then I seen a similar example using a TreeSet. I was just curious.. what's the recommended way to do this?
(Complete code here: http://pastebin.com/GdDmCWj0 )
You said "had a homework assignment" so I'm assuming you're done with this.
I would do it a bit differently. Firstly, I think some of the keywords in your
String
array were incorrect. According to Wikipedia and Oracle, Java has 50 keywords. Anyway, I've commented my code fairly well. Here's what I came up with...Every time I encounter a keyword from the file, I first check if its in the Map; if it isn't, its not a valid keyword; if it is, then I update the value the keyword is associated with, i.e., I increment the associated
Integer
by 1 because we've seen this keyword once more.Alternatively, you could get rid of that last for loop and just keep a running count, so you would instead have...
... and you print out the counter at the end.
I don't know if this is the most efficient way to do this, but I think its a solid start.
Let me know if you have any questions. I hope this helps.
Hristo
Try a
Map<String, Integer>
where the String is the word and the Integer is the number of times the word has been seen.One benefit of this is that you do not need to process the file twice.