I'm writing a program that reads in a text file line by line - then stores each sentence in a HashMap with the sentence as the key and number of letters in that sentence as the object. This is the code I wrote, with comments:
FileReader reader = new FileReader(new File("src/test.txt"));
BufferedReader br = new BufferedReader(reader);
HashMap<String, Integer> map = new HashMap<String, Integer>();
StringBuilder builder = new StringBuilder();
String line, sentence;
int letters = 0;
try {
// While there are more lines to read
while ((line = br.readLine()) != null) {
String[] words = line.split(" "); // split line into words, add to array
for (int i = 0; i < words.length; i++) { // loop through array
letters += words[i].length();
// if the word ends with "." then we have reached end of sentence
if (Character.toString(words[i].charAt(words[i].length() - 1)) == ".") {
for(String word : words) {
if(builder.length() > 0) {
builder.append(" ");
}
builder.append(word);
}
sentence = builder.toString(); // store sentence
map.put(sentence, letters); // add to HashMap
letters = 0; // restore letters back to 0
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
for(String key : map.keySet()) {
System.out.println(key + " has " + map.get(key) + " letters");
}
For some reason in that little for-loop at the end nothing gets printed. I notice that if I write a print statement before the for-loop to print out the size of my HashMap it prints out "0" - so I'm assuming that my HashMap isn't being populated.
Does anyone know why this might be the case? This is the text file I'm using:
this is a test.
this is a test.
this is not a test.
this is a test.
this is not a test.
not not not not not not not
Really appreciate any insight, cheers.