0

I have done this code:

Table tb;
Exam[] examArr;
int day, month, year, lengt;
String subject, room;
Date d;
lengt = reader.nextInt();
examArr = new Exam[lengt];
for(int i = 0; i<testArr.length; i++)
{
     System.out.println("Enter day, month, year.");
     day = reader.nextInt();
     month = reader.nextInt();
     year = reader.nextInt();
     d = new Date(day, month, year);
     System.out.println("Enter subject.");
     subject = reader.next();
     examArr[i] = new Exam(subject, d);
}
System.out.println("Enter room.");
room = reader.next();
tb = new Table(room, examArr);
System.out.println(tb.toString());

I get an exception that says NullPointerException at Table.toString(Table.java:43). I go to the Table class that has: private Test[] arr; private String room; The toString() method is:

String s = "";
for(int i = 0; i<this.arr.length;i++)
{
     s += arr[i].toString();
}
return s;

The program marks the line s += arr[i].toString(); in yellow. The toString() of Exam is

return subject + " " + this.testDay.toString();

The toString() of Date is

return day+"/"+month+"/"+year;

I think I'm giving the needed information.

cryptic_star
  • 1,863
  • 3
  • 26
  • 47
user139316
  • 103
  • 1
  • 1
  • 4
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – VGR Oct 27 '15 at 19:50
  • @VGR Nope. I have read those. – user139316 Oct 27 '15 at 19:53

3 Answers3

0

The problem is:

System.out.println(tb.toString());

What is Table class, you can't use toString for that class because the tb variable is null

Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
0

The problem could be in:

...

for(int i = 0; i<this.arr.length;i++)
{
     s += arr[i].toString();
}

...

as you iterate through this.arr but you use arr[i].toString() did you by any change mean this.arr[i].toString() ? Also check if your array contains something else than nulls.

-2

Always check if the object is null before calling it's methods

String s = "";
for(int i = 0; i<this.arr.length;i++)
{
 if(arr[i]!=null)
 s += arr[i].toString();
}
return s;
snaikar
  • 415
  • 4
  • 12