I'm trying to create a code that searches for a given name on the list. Afterwards, it should print "found" or "not found". If the user enters an incorrect file, the code should print, "Reading the file " + file + " failed.". However, it prints the error message, even when the name IS found. I'm guessing its a syntax error, but I spent 45 minutes trying to find it. Here is my code:
import java.nio.file.Paths;
import java.util.Scanner;
public class IsItInTheFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name of the file:");
String file = scanner.nextLine();
System.out.println("Search for:");
String searchedFor = scanner.nextLine();
boolean value=false;
try(Scanner fhandle=new Scanner(Paths.get(file))){
while(fhandle.hasNextLine()){
String line = fhandle.nextLine();
while(!(line.isEmpty())){
//System.out.println("Current line is "+line);
String[] words=line.split(" ");
for(String word:words){
if (word.equals(searchedFor)){
value=true;
//System.out.println(word);
}
}
line=fhandle.nextLine();
}
}
}catch(Exception e){
System.out.println("Reading the file " + file + " failed.");
}
if(value){
System.out.println("Found!");
}else{
System.out.println("Not found.");
}
}
}