Mark Said Camilleri
Mark Said Camilleri

Reputation: 388

Java.NullPointerException null (again)

I am having another problem with NullPointerException. This time it is highlighting tellen = telno.length(). Beore you ask:

Please help. Thanks. Text file:

Problem is in the telephone (tellen) All these names are fictional, and this program is a telephone directory

George
Farrugia
Some Company 
9, Flowers
Quail Street
Bubaqra
BBQ 1569
21369854
79825643
--------------------------------------------
Paul
Zammit

9
Bird Street
St. Julians
STJ 0000
21545796
79745247
--------------------------------------------
Peter
Spiteri
Oak Company
Trees
Birch Street
Oakgrove
TRE 3333
21323323
99323323
--------------------------------------------

The blank after Zammit is a space. That is placed if there is no data to avoid a problem like this.

Upvotes: 1

Views: 562

Answers (4)

Smit
Smit

Reputation: 4715

This error is getting caused because you are reading 11 lines in one while loop instead you have to read 10 lines only.

So at some point br.readLine() will return null.

You need to read file according to your need that means in one go (your while loop) read 10 lines, then next 10 lines and so on.

while((telno = br.readLine()) != null){ // first line
    name = br.readLine();   // secondline I think this should be first line

    surname = br.readLine();

    company = br.readLine();

    house = br.readLine();

    street = br.readLine();

    locality = br.readLine();

    postcode = br.readLine();

    telno = br.readLine();
    tellen = telno.length();

    mobno = br.readLine();

    sep = br.readLine();  // eleventh line

    if(tellenx > tellen) tellen = tellenx;


}

Upvotes: 1

Brian Var
Brian Var

Reputation: 6227

Adding an if statement to check if there is any null references is a good practice to check for an error in your code.

An example in pseudo code would be:

   telno = br.readLine();

   if(telno == null)
       System.out.println("this will cause null pointer exception  "+ telno.length()); 
   else
       tellen = telno.length();

Upvotes: 0

Renjith
Renjith

Reputation: 3274

I guess you are trying to read using readLine() without null check.Definitel, it will give NPE.

Upvotes: 0

PermGenError
PermGenError

Reputation: 46438

Most probably its the end of the file and your bufferedReader.readLine() is returning null and you just invoked a method on an instance which is null, which leads to NPE.

Upvotes: 1

Related Questions