带数组的 getMethod

getMethod with an array

我似乎无法弄清楚为什么这不起作用。犁是我在另一个 class 文件中制作的构造函数,但我希望能够分配它,以便我以后可以通过为我的构造函数

使用数组来更改犁的数量
                 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)

有了这个:

 Plow[] plows = new Plow[PLOWS];

您正在实例化一个包含 Plow 个对象的新数组。但是此时,数组会被初始化为PLOWS项,但里面的所有项都会是null。每个项目都需要自己初始化。

所以当你到达这一部分时:

 plows[a].setPlowID(plowID); 

plows[a] 为空,因此运行时异常。

一个可能的解决方案是在 while 块内,在尝试之前添加:

if (plows[a] == null) plows[a] = new Plow();

编辑:正如@StenSoft 指出的那样,NPE 还有另一个原因,当 while 循环(以及后来的 close() 调用)尝试使用 FileInputStream;如果文件不存在,您只需捕获异常而不恢复(或中断),然后继续处理:流将为 null,您将得到另一个 NullPointerException。将 while 循环移动到 try catch 中,然后放置 close() 调用的最佳位置是在 finally.