shri
shri

Reputation: 47

NullPointer Exception while performing string split

I am getting input from a file. The file has two columns. I want to store each column in an array. This is what i'm doing.

   String strArr;

    for(int x=0;x<=m;x++){  // m is the number of lines to parse

      strArr = bufReader.readLine(); 
     String[] vals=strArr.split("\\s+ ");
      System.out.println(strArr);

    nodei[x]=Integer.parseInt(vals[0]);
    nodej[x]=Integer.parseInt(vals[1]);

      }

I encounter NullPointerException at

String[] vals=strArr.split("\\s+ ");

How do I resolve?

Upvotes: 0

Views: 478

Answers (1)

Moishe Lipsker
Moishe Lipsker

Reputation: 3032

if strArr is null, and you call .split on it, it will throw a null pointer. You can check if null before using .split.

String strArr;

for(int x=0;x<=m;x++){  // m is the number of lines to parse

  strArr = bufReader.readLine(); 
  if (strArr != null) {
      String[] vals=strArr.split("\\s+ ");
      System.out.println(strArr);

      nodei[x]=Integer.parseInt(vals[0]);
      nodej[x]=Integer.parseInt(vals[1]);
  }
}

Upvotes: 1

Related Questions