The idea is simple:
- Load a text file into a string.
- Split this string into paragraphs.
- Split all paragraphs into words.
- Add each individual word to an ArrayList.
The result is an ArrayList containing all of the words in the text file.
The procedure works; it loads all of the words in an ArrayList fine.
HOWEVER, any "IF" statements to find a specific item in the ArrayList do not work.
EXCEPT: if the word is a newline.
public String loadText(String resourceName){
// Load the contents of a text file into a string
String text = "";
InputStream stream = FileIO.class.getResourceAsStream(resourceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String str = "";
try {
while ((str = reader.readLine())!=null){
text += str + "\n";
}
} catch (Exception e) {
System.out.println("Unable to load text stream!");
}
return text;
}
public void test(){
ArrayList<String> collectionOfWords = new ArrayList<String>();
String text = loadText("/assets/text/intro.txt");
// Split into paragraphs
String paragraphs[] = text.split("\n");
for (String paragraph: paragraphs){
// Split into words
String words[] = paragraph.split(" ");
// Add each word to the collection
for (String word: words){
collectionOfWords.add(word);
}
// Add a new line to separate the paragraphs
collectionOfWords.add("\n");
}
// Test the procedure using a manual iterator
for (int i=0; i<collectionOfWords.size(); i++){
// ===== WHY DOES THIS WORK?
if (collectionOfWords.get(i)=="\n")
System.out.println("Found it!");
// ===== BUT THIS DOESN'T WORK???
if (collectionOfWords.get(i)=="test")
System.out.println("Found it!");
// NOTE: Same problem if a I use:
// for (String word: collectionOfWords){
// if (word=="test")
// System.out.println("Found it!");
}
}
Sample of text file: The Quick Brown\n Fox Jumps Over\n test the lazy dog\n
Any ideas? I am at the point to just scratch my design and try something totally different...