2

I'm trying to run this code. It reads the file successfully, but breaks at the word search itself.

The error:

Exception in thread "main" java.lang.NullPointerException
        at WordSearch.main(WordSearch.java:30)  

Here's the code:

import javax.swing.JOptionPane;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;


public class WordSearch{

public static void main(String[] args) throws FileNotFoundException{

    String searchWord, fileName; int i=0, j=0;

    fileName = JOptionPane.showInputDialog(null, "Please enter the name of the file to be processes: ");
    File textFile = new File(fileName);

    Scanner scanner = new Scanner(textFile);

    String[] file = new String[500];
    String[] found = new String[500]; 

    while(scanner.hasNextLine()){
        file[i]=scanner.next();
        i++;
    }

    file[i+1]="EoA"; i=0;

    searchWord = JOptionPane.showInputDialog(null, "Please input the string to search for: ");

    while(!file[i].equals("EoA")){
        if (file[i].equals(searchWord)){
            if(i==0){
                found[j]=file[i]+file[i+1]+"\n";
            }
            else if(i==500){
                found[j]=file[i-1]+file[i]+"\n";
            }
            else {
                found[j]=file[i-1]+file[i]+file[i+1]+"\n";
            }

            j++;
        }
        i++;
    }

    JOptionPane.showMessageDialog(null, found);
}
}

2 Answers 2

2

Change

file[i+1]="EoA";

to

file[i]="EoA";

Otherwise, you'll have a null entry in the position that precedes the "EoA" entry, which causes the NullPointerException.

Of course, you can get rid of the "EoA" entry, and just change the loop's condition to :

while (file[i] != null)

That's much more readable.

One last thing, how do you guarantee that your input won't be larger than the 500 length of your array?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Working with arrays and stuff in Java is really getting at me after having such an easy time in C :(
I'd use an ArrayList if I wanted the code to actually be practical.
0

This is happening because of your i++ expression. In each iteration i is being incremented and the result gets stored in previous index pointed by the value of i

Possible solution is to use i-1 in the while loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.