Null Pointer Exception? [duplicate]

0

In the code snippet below, you are supposed to compare the value of items in array linhas with String entered by user p . It's working, but it always gives the error:

  

Stack trace - Exception in thread "main" java.lang.NullPointerException   at MainSwitch.main (MainSwitch.java:229)

The code:

String guardar;
String lista[] = new String [tamMax];

System.out.println("Insira a palavra que pretende pesquisar:");
p = reader.next();

for(int i = 0; i < linhas.length; i++)
{
    guardar = linhas[i];
    lista = guardar.split(" ");  //linha do erro
    for(int k = 0; k < lista.length; k++)
    {
        if(lista[k].equals(p))
        {
            System.out.println("Linha " + i + ": " + linhas[i]);
        }
    }
}
    
asked by anonymous 01.12.2018 / 02:59

1 answer

0

This error java.lang.NullPointerException indicates that you are trying to use something that is null .

That in your case, by what has been posted, indicates that some index of linhas is null .

In the posted code does not show the statement or how it is being filled.

However, you can solve part of the problem by putting a check before using the item, such as if( linhas[i] == null ) continue;

The continue returns to the nearest for and causes it to continue with the next index i

guardar = linhas[i];
if( guardar == null ) continue;
lista = guardar.split(" ");

Now you should check your code as this array is being filled.

    
01.12.2018 / 05:11