I'm currently writing an app for school that is a mini search engine. On execution, it indexes the contents of the text files included as args. I haven't used the try and catch methods before, and we were just given this code in include in our program:
Scanner inputFile = null;
try {
inputFile = new Scanner(new File("dog.txt"));
} catch (FileNotFoundException fe) {
System.out.println("File not found!");
}
I've created a method that loops through the args and adds a new object to an array for every unique word found. The problem is that the catch method seems to still execute whenever I run the app, and I can't work out why. This is the output:
dog.txt being indexed ... File not found!
cat.txt being indexed ... File not found!
I've included the method below. If anyone cold maybe point out where I'm going wrong, that would be great.
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!");
}
}
}