我目前正在尝试构建一个时钟程序来练习构建类和存储文本数据。我当前得到一个nullPointerException,虽然我相信我正确地初始化了TimeClock数组。
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;
}
我一直收到错误:
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
答案 0 :(得分:0)
在Java中初始化数组只需创建给定大小的null
s数组。在使用之前,您仍需要显式初始化每个元素:
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++;
}
答案 1 :(得分:0)
所有临时数组元素都为null。如果是第一个,你必须初始化它们。
...
temp[count] = new TimeClock();
temp[count].setInTime( Long.parseLong(data1) );
...