Null Pointer Exception?

Asked

Viewed 395 times

0

In the code snippet below, you are supposed to compare the value of the items in the array linhas with the String inserted by the user p. It’s working, but there’s always 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]);
        }
    }
}
  • Place the stacktrace and point with a comment in the code the problem line.

  • Exception in thread "main" java.lang.Nullpointerexception At mainswitch.main(Mainswitch.java:229) The error is in the split line - list = save.(" ");

  • Always good to check this: https://answall.com/q/63617/64969; read all the answers. The problem is that its vector linhas was initialized but not populated, therefore for some index i we have to lista[i] == null

  • I get it.. And what’s the best way to solve this?

  • By the way, if you want to use comments //, leave the code on the left, otherwise the code becomes part of the comment

  • Done, my rsrs mistake

  • After this line guardar = linhas[i]; tries to put if( guardar == null ) continue;

Show 2 more comments

1 answer

0


That mistake java.lang.NullPointerException indicates that you are trying to use something that is null.

Which in your case, from what was posted, indicates that some index of linhas is null.

No code posted shows the declaration or how it is being filled in.

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

The continue back to for above closer and makes it continue with the next index i

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

Now you better check your code like this array this being filled.

  • 1

    The problem is in the method that is inserting strings into the array, it is skipping the first line of the array. Thank you very much for the explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.