我似乎无法弄清楚为什么这不起作用。犁是我在另一个类文件中创建的构造函数,但是我希望能够分配它,以便稍后我可以通过为构造函数使用数组来更改犁的数量
static int PLOWS=4
public static final String PLOW_DATA = "PlowData.txt";
public static void getPlowData(){
Plow[] plows = new Plow[PLOWS];
Scanner fileIn = null;
int a = 0;
int plowID;
String driver;
System.out.println("Reading Files....");
try
{
fileIn = new Scanner(new FileInputStream(PLOW_DATA));
System.out.println("File Found!");
}
catch (FileNotFoundException e)
{
System.out.println("Error: file '" + PLOW_DATA + "' not found.");
}
while (fileIn.hasNext())
{
//System.out.println("Writing...");
try{
plowID = fileIn.nextInt(); //reading plow ID
System.out.print(plowID+"\t");
plows[a].setPlowID(plowID);
}
catch (java.util.InputMismatchException e){
driver = fileIn.nextLine(); //reading Driver
System.out.println(driver);
plows[a].setDriver(driver);
}
a++;
}
fileIn.close();
System.out.println("Done!");
}
运行时出现此错误
10 Exception in thread "main" java.lang.NullPointerException
at um.csc276.JavaHomework4.HW4_1.getPlowData(HW4_1.java:63)
at um.csc276.JavaHomework4.HW4_1.main(HW4_1.java:149)
答案 0 :(得分:0)
有了这个:
Plow[] plows = new Plow[PLOWS];
您正在实例化一个新的Plow
个对象数组。但此时,数组将初始化为PLOWS
个项目,但其中的所有项目都将为null
。每个项目都需要自己初始化。
所以当你到达这个部分时:
plows[a].setPlowID(plowID);
plows[a]
为null,因此是运行时异常。
可能的解决方案是在while块内,在try之前添加:
if (plows[a] == null) plows[a] = new Plow();
编辑:正如@StenSoft指出的那样,NPE还有另一个原因,当while循环(以及后来的close()调用)尝试使用FileInputStream
;如果文件不存在,你只需捕获异常而不恢复(或中断),然后继续处理:流将为null,你将得到另一个NullPointerException。在try catch中移动while循环,然后将close()
调用放在finally
内的最佳位置。