juliodesa
juliodesa

Reputation: 51

Method that returns all line numbers a word occurs in a text file

I am writing a method that returns all line numbers a word occurs in a text file. For example, if "hello" is the parameter, it'll search my text file and return all line numbers "hello" occurs in.

If my test file says:

Hello
my name is
is Java.

and my parameter for the method is "my", it should return:

[2,3]

However, I am getting this error:

Exception in thread "main" java.lang.NullPointerException
at Indexer.lineNumbers(Indexer.java:41)
at Indexer.main(Indexer.java:22)

Here is my code:

public static String lineNumbers(String x) throws FileNotFoundException, IOException
   {
            LineNumberReader lineReader = new LineNumberReader(new FileReader("File.txt"));
            Scanner fileScanner = new Scanner(new File("File.txt"));
            String numbers = "[";
            while (fileScanner.hasNextLine())
            {
               String line = lineReader.readLine();
               if (line.contains(x))
               {
                  int lineNumber = lineReader.getLineNumber();
                  String numberString = Integer.toString(lineNumber);
                  numbers = (numbers + "," + numberString);
               }
            }
            return numbers + "]"; 
   }

What am I doing wrong?

Upvotes: 1

Views: 1349

Answers (2)

ThisClark
ThisClark

Reputation: 14823

An alternative you may consider puts the line numbers in an ArrayList that you can then iterate over in another process:

public static ArrayList<Integer> lineNumbers(String x) 
        throws FileNotFoundException, IOException {
    ArrayList<Integer> lineNumbers = new ArrayList<Integer>();
    Scanner fileScanner = new Scanner(new File("File.txt"));
    int lineNumber = 0;
    while (fileScanner.hasNextLine()) {
        String line = fileScanner.nextLine();
        lineNumber++;
        if (line.contains(x)) {
            lineNumbers.add(lineNumber);
        }
    }
    return lineNumbers;
}

Then try looping over the values you get like this:

String searchFor = "is";
for(int i : lineNumbers(searchFor)) {
    System.out.println(i);
}

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53535

You're trying to read the same file using a scanner and a line-reader so you end up stepping on your own toes.

Try this:

public static String lineNumbers(String x) throws IOException
{
    LineNumberReader lineReader = new LineNumberReader(new FileReader("/Users/alfasi/tpstats-eu-west-1.log"));
    String numbers = "";
    String line;
    while ((line = lineReader.readLine()) != null)
    {
        if (line.contains(x))
        {
            numbers += "," + lineReader.getLineNumber();
        }
    }
    return "[" + numbers.substring(1) + "]";
}

Upvotes: 3

Related Questions