我目前正在为一个迷你搜索引擎的学校编写一个应用程序。在执行时,它将包含为参数的文本文件的内容编入索引。我没有用之前的try
和catch
方法,而我们只是给这个代码作为我们的节目包括:了解Java的尝试/赶上
Scanner inputFile = null;
try {
inputFile = new Scanner(new File("dog.txt"));
} catch (FileNotFoundException fe) {
System.out.println("File not found!");
}
我已经创建了通过ARGS循环,并增加了一个新对象的方法找到每个唯一字的数组。问题是catch
方法似乎仍然执行,每当我运行该应用程序,我不能解决原因。这是输出:
dog.txt被索引...文件未找到!
被索引的cat.txt ...文件未找到!
我已经包括下面的方法。如果有人感冒可能指出我要出错的地方,那会很好。
static void createIndex(String[] args) {
for(int i = 0; i < args.length; i++) {
Scanner inputFile = null;
try {
System.out.print((args[i]) + " being indexed ... ");
inputFile = new Scanner(new File(args[i]));
while(inputFile.hasNext()) {
boolean isUnique = true;
String newWord = inputFile.next().trim().toLowerCase();
for(int j = 0; j < uniqueWords; j++)
if(newWord.equals(wordObjects[j].getWord())) {
wordObjects[j].setFile(args[i]);
isUnique = false;
}
if(isUnique) {
wordObjects[uniqueWords] = new WordIndex(newWord, args[i]);
uniqueWords++;
}
}
System.out.print("done");
} catch(FileNotFoundException fe) {
System.out.println("File not found!");
}
}
}
谢谢大家。我以为是因为它打印了它找到的文件的名字......显然它是从我写的参数中得到的。所以移动这些文件并交换了你们所指出的两行代码,并且工作正常! – 2009-08-09 07:34:57
我建议尽可能使用尽可能少的代码来包装try块。在这种情况下,这并不重要,但由于您只希望在前几行中引发FileNotFoundException,请将try块放在那里,而不是放在循环的整个内容中。如果没有找到该文件,则尝试执行循环的其余部分没有多大意义,因此可以在catch块中放置“continue”。另一方面,太多的“继续”代表意大利面代码,所以要小心。 – MatrixFrog 2009-08-09 19:26:19
例外是告诉你没有找到文件。那么你知道那些'.txt'文件在哪里吗?你可以在当前目录中看到它们吗? – 2009-08-09 07:17:30