Skip to content
Advertisement

how to properly get every line containing a specific word in java

I’m trying to write a program that reads a file and checks every line that contains a specific word then prints it.if there isn’t one it should print “no match for your search”.this is what I’ve got so far and and I’m having trouble putting it all together.after all my twinkering around and replacing thewhile with ifor putting the second if statement outside of the while, sometimes it doesn’t matter what i enter it always says “no match for your search” and sometimes it says java.util.NoSuchElementException: No line found. and sometimes it freezes and i searched this up and it says its a bug in cmd or something.any help will be appreciated and I’m new to java so please any thing you can advise me will be helpful and appreciated

System.out.println("search for book");
 
String search = scan.next();    
scan.nextLine();    

File file = new File("library.txt");
Scanner in = null;
in = new Scanner(file);
          
String line = in.nextLine();
while(in.hasNext()) {
    if(line.contains(search)) {
        System.out.println(line);
    }   
           
    if(!line.contains(search)) {
        System.out.println("no match for your search");
        System.exit(0);
    }
}

Advertisement

Answer

First of all you seem to skip your first line. Secondly, second if clause is redundant.

Boolean found=false;
while(in.hasNext()) {
    String line = in.nextLine();
    if(line.contains(search)) {
        System.out.println(line);
        found=true;
    }           
}

if(found==false) System.out.println("no match for your search");
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement