我正在编写一个逐行读入文本文件的程序 - 然后将每个句子存储在HashMap中,并将句子作为关键字,将该句子中的字母数作为对象。这是我写的代码,带有注释:
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循环中没有任何东西被打印出来。我注意到如果我在for循环之前写一个print语句来打印出我的HashMap的大小,它打印出“0” - 所以我假设我的HashMap没有被填充。
有谁知道为什么会这样?这是我正在使用的文本文件:
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
非常感谢任何见解,欢呼。