我写了一个程序来接受来自文本文件的输入,并以升序显示文件中的单词而没有重复。如果没有抛出异常,则输出正确。如果抛出异常,则要求用户输入有效输入并重复初始方法。发生这种情况时,最后输入有效输入,输出将重复。
我知道有些东西没有被重置,但我无法弄清楚它是什么。
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]);
}
}
答案 0 :(得分:1)
当您从catch块调用go()
时,您忘记原始go()
调用仍在堆栈中。它不会因为您再次调用该方法而消失。基本上,你正在进行一些意外的递归。
所以在这种情况下,你第二次打电话给go()
,它将按照正常情况执行,然后堆栈将&#34;放松&#34;并执行go方法第一次调用的剩余部分,打印出wordlist,对其进行排序,然后再将其打印出来。
快速修复可能是让getWords()
返回一个布尔值(如果抛出异常则为false),然后将第一行更改为while(!getWords());
。
答案 1 :(得分:0)
这是因为你在catch块中调用go,方法导致再次打印输出,你可以像这样纠正它,
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.");
getwords(); //Changed
}
}
void addWord(String lineToParse) {
String[] tokens = lineToParse.split("\\s");
for(int i = 0; i < tokens.length; i++) {
wordList.add(tokens[i]);
}
}