我正在尝试根据我在side2[]数组中的对象来编写一个新文档。不幸的是,这个数组中的一些索引是空的,当它击中其中一个索引时,它只会给我一个NullPointerException。这个数组有10个索引,但在本例中并不需要所有索引。我已经尝试过try catch语句,希望在遇到null后继续执行,但它仍然停止执行,并且不会编写新文档。作为对象的一部分的堆栈(srail)包含我要打印出来的数据。
这是我的代码:
    // Write to the file
    for(int y=0; y<=side2.length; y++)
    { 
        String g = side2[y].toString();
        if(side2[y]!=null){
            while(!side2[y].sRail.isEmpty())
            {
                out.write(side2[y].sRail.pop().toString());
                out.newLine();
                out.newLine();
            }
            out.write(g);
        }
    }
    //Close the output stream/file
    out.close();
}
catch (Exception e) {System.err.println("Error: " + e.getMessage());}发布于 2013-11-04 00:10:31
问题是,在检查side2[y]对象是否存在null之前,代码会在该对象上调用null。通过在循环顶部添加一个条件,可以跳过null对象,如下所示:
for(int y=0; y<=side2.length; y++) {
    if(side2[y] == null) {
        continue;
    }
    String g = side2[y].toString();
    // No further checks for null are necessary on side2[y]
    while(!side2[y].sRail.isEmpty()) {
        out.write(side2[y].sRail.pop().toString());
        out.newLine();
        out.newLine();
    }
    out.write(g);
}https://stackoverflow.com/questions/19759813
复制相似问题