Question

It seems my search method only searches the first line, nothing else. not sure why. It should read line by line for a match, and if not found there move onwards to the next line until all line are exhausted, but when I test it with a file that has more than one line and search for a string on say line 5 it returns: Search parameter NOT found in file.

String Search(String key) throws IOException {

int lines = 0;
String line = "";
String nextLine = "";
String foundAt = "";
BufferedReader BR = new BufferedReader(new FileReader(f));

try  {
   while ((nextLine = BR.readLine()) != null) {
      line = nextLine.toLowerCase();
      lines++;
      StringTokenizer words = new StringTokenizer(line); //create tokenizer words with what is in line
      while(words.hasMoreTokens()) { //while words has tokens left
         if (words.nextToken().equals(key.toLowerCase())) //go to next token and compare to key
            foundAt = foundAt + "\n" + lines + ": " + line;

            //do nothing continue loop                     
         }
      }
      BR.close();
   }  catch(FileNotFoundException e)  {
   }
   if (foundAt == "")
   foundAt = "Search parameter NOT found in file.";
   return foundAt;
}
Was it helpful?

Solution

I see absolutely no problem with the code, I tried it with the following test file:

word line
number two
alice and bob
bar bazz
loop for each
buzz bizz bar bozz
this is some text
lorem ipsum bar
buzz isobar

And searched for "bar":

System.out.println(Search("bar"));

And I got the following (expected) result:

4: bar bazz
6: buzz bizz bar bozz
8: lorem ipsum bar

So, it's correctly identifying the lines containing the word (it even skips the last line containing "bar" as part of another word).

My best guess is that you are passing a wrong file path, so you have a FileNotFoundException, but as you are ignoring it, you have no stack trace, and nothing to help you. Try to print the exception in the catch clause, and re-run you program:

catch(FileNotFoundException e)
{
    e.printStackTrace();
}

My second best guess is that your test case is bad (like if the string you are searching is part of another word, or if you have some punctuation just after the word). Try to run my test case, and see if it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top