我编写了一个程序来接受来自文本文件的输入,并以升序显示文件中的单词,没有重复。如果没有抛出异常,则输出是正确的。如果抛出异常,则要求用户提供有效输入并重复初始方法。当这种情况发生时,最终输入了一个有效的输入,输出就会被复制。
我知道某些东西没有被重置,但我无法弄清楚它是什么。
public void go() {
getWords();
System.out.println(wordList);
wordList = new ArrayList<String>(new HashSet<String>(wordList));
Collections.sort(wordList);
System.out.println(wordList);
}
void getWords() {
try {
File file = new File(getInput());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
addWord(line);
}
} catch(Exception ex) {
System.out.println("Invalid file name, try again.");
go();
}
}
void addWord(String lineToParse) {
String[] tokens = lineToParse.split("\\s");
for(int i = 0; i < tokens.length; i++) {
wordList.add(tokens[i]);
}
}