-4

I'm currently trying to build a time clock program to practice building classes and storing text data. Im currently getting a nullPointerException although I believe I initialized the TimeClock array temp properly.

public TimeClock[] readFile(){
    try{
        read = new Scanner(new File("TimeClockData.txt") );
    } catch (Exception e){
        System.out.println("could not find file");
    }

    TimeClock[] temp = new TimeClock[100];
    int count = 0;
    String data1;
    String data2;
    String data3;
    while(read.hasNext() ){

        data1 = read.next();
        data2 = read.next();
        data3 = read.next();

        temp[count].setInTime( Long.parseLong(data1) );
        temp[count].setOutTime( Long.parseLong(data2) );
        temp[count].setNotes(data3);

        count++;

    }

    read.close();

    return temp;
}

I keep getting the error:

Exception in thread "main" java.lang.NullPointerException
    at timeclock.pkg2.ReadFile.readFile(ReadFile.java:46)
    at timeclock.pkg2.Timeclock2.main(Timeclock2.java:56)
Java Result: 1
Chris Chevalier
  • 620
  • 1
  • 7
  • 20

2 Answers2

0

Initializing an array in Java just create an array of nulls in the given size. You still have to explicitly initialize each element before you use it:

while(read.hasNext() ){

    data1 = read.next();
    data2 = read.next();
    data3 = read.next();

    temp[count] = new TimeClock(); // Was missing in the OP code
    temp[count].setInTime( Long.parseLong(data1) );
    temp[count].setOutTime( Long.parseLong(data2) );
    temp[count].setNotes(data3);

    count++;

}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

All your temp array elements are null. You have to initialize them if first.

...
temp[count] = new TimeClock(); 
temp[count].setInTime( Long.parseLong(data1) );
...
Juru
  • 1,623
  • 17
  • 43