So I need help fixing this code, or more so understanding its faults. The code itself is supposed to read a file and print out the of occurrence of a string of words. However, it seems that it always prints out "Can't find file" even when the .txt file is on my desktop.
import java.util.*;
import java.io.*;
/**
* Searcher
*/
public class Searcher extends File {
Scanner scn;
public Searcher(String filename) {
super(filename);
}
public void search(String input) {
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
}
int count = 0, fromIndex = 0;
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
public static void main(String[] args) {
Searcher search = new Searcher("ihaveadream.txt");
search.search("slavery");
}
}