基本上,该程序应该搜索文本文件并查找出现的不同单词的数量,然后将它们存储在数组中,然后向用户显示单词和次数。我尝试使用map类,但由于它不会显示结果而未能成功。所以我想知道是否有人知道我可以修复此文件的其他方式:
public class WordStats {
public static void main(String[] args) {
File textFile = new File("words.txt");
FileReader in;
BufferedReader readFile;
char charInFile;
String newWord = "";
String map=new String();
String existingMap=new String();
int wordIndex, index = 0;
ArrayList wordList = new ArrayList();
/* navigating the file */
try{
in = new FileReader(textFile);
readFile = new BufferedReader(in);
do{
charInFile = (char)readFile.read();
if(charInFile >= 'a' && charInFile <= 'z'){
while(charInFile >= 'a' && charInFile <= 'z'){
newWord += charInFile;
charInFile = (char)readFile.read();
}//end of while
wordIndex = wordList.indexOf(map);
if(wordIndex > -1){
existingMap = (String) wordList.get(wordIndex);
//existingMap.addOccurrence();
wordList.set(wordIndex, existingMap);
} else {
index = 0;
}
if(wordList.size() > 0){
do{
existingMap = (String) wordList.get(index);
index += 1;
}while(existingMap.compareTo(map) <= 0 && index <
wordList.size());
wordList.add(index-1, map);
}else{
wordList.add(map);
}
}//end of if
newWord = "";
}while(charInFile != (char)-1);
System.out.println("Word\t\tOccurrences");
for(Object Word : wordList){
System.out.println(Word);
}
readFile.close();
in.close();
}catch(FileNotFoundException e){
System.out.println("file could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
}catch(IOException e){
System.out.println("problem reading the file.");
System.err.println("IOException: " + e.getMessage());
}
}
}