We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all,
I am looking to load a text file and search for a specific word and the number of times it appears. The following code produces a list of all the individual words, however when I try to run an if statement for a specific word, it returns nothing even when the word is present in the list.
String[] lines = loadStrings("2012_0806.txt");
int wordCount = 0;
String[] words;
String searchTerm = "risk";
for (int i = 0; i < lines.length; i++) {
String separators = WHITESPACE + ",;.:?()\"-";
words = splitTokens(lines[i], separators);
wordCount += words.length;
for (int j = 0; j < words.length; j++) {
String word = words[j].toLowerCase();
// println(word); // this prints all the individual words -- "risk" is on here 3 times
if (word == "risk") {
println("success");
}
}
}
Answers
You should never use == when comparing Strings. Always use the equals() method instead. Do a google search of "Java String equality" for more info.
Thanks for the information, that solved my issue.
Also, I have no idea what you're doing, but you might consider looking at the ArrayList.contains() method as well as the String.equalsIgnoreCase() method.
Thanks, my goal is just search through a text file and count the number of times a specific word appears.
Sounds good. There are a ton of different ways to do that (depending on if you only care about one word, or want the word counts of every word, or the most popular word, etc). Data structures like ArrayList and Map can help you, but if you only care about a single word, then they might be overkill. Good luck!
Thanks again!