Question

So I have an assignment that requires me to "Search a file line by line for a given string. The output must contain the line number, and the line itself, for example if the word files was picked the output look something like

5: He had the files
9: the fILEs were his

Code:

void Search(String input) throws IOException {
    int x = 1;
    FileReader Search = new FileReader(f);
    Scanner in = new Scanner(f);
    LineNumberReader L = new LineNumberReader(Search, x);
    StreamTokenizer token = new StreamTokenizer(Search);
    while (in.hasNextLine())
    {
        try
        {
            if (!in.findInLine(input).isEmpty())
            {
                display(Integer.toString(L.getLineNumber()) + ": " + L.readLine(), "\n");

                in.nextLine();
            }

        } catch (NullPointerException e)
        {
            System.out.println("Something Happened");
            in.nextLine();
        }
    }
}

So far there are 3 issues I need to figure out with my code.

  1. As soon as instance occurs where the searched is not in a line, it immediately displays the next line, even though the searched word is not in the line, and then terminates from there without having displayed the rest of the lines that had the word in it.
  2. It supposed to display lines with the word, regardless of casing, but does not.
  3. Preferably, it's supposed to display all of them at once, but instead is displaying line by line, until it errors out and terminates.

No correct solution

OTHER TIPS

You're main problem is here...

FileReader Search = new FileReader(f);
Scanner in = new Scanner(f);
LineNumberReader L = new LineNumberReader(Search, x);
StreamTokenizer token = new StreamTokenizer(Search);
while (in.hasNextLine())
{

You've basically opened two file readers against the same file, but you seem to be expecting them to know about each other. You advance the Scanner, but that has no effect on the LineNumberReader. This then messes up the reporting and line reading process.

Reading from Scanner should look more like...

while (in.hasNextLine()) {
    String text = in.nextLine();

Having said that, I'd actually drop the Scanner in favor of the LineNumberReader as it will provide you with more useful information which you would otherwise have to do yourself.

For example...

FileReader Search = new FileReader(new File("TestFile"));
LineNumberReader L = new LineNumberReader(Search, x);

String text = null;
while ((text = L.readLine()) != null) {
    // Convert the two values to lower case for comparison...
    if (text.toLowerCase().contains(input.toLowerCase())) {
        System.out.println(L.getLineNumber() + ": " + text);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top