gpt4 book ai didi

java - 抛出 NullPointerException,但对象已创建并正确返回值

转载 作者:行者123 更新时间:2023-11-30 06:01:23 25 4
gpt4 key购买 nike

正在开发一个程序,该程序具有保存在文件夹中的形状库和说明文件(描述绘图的细节)。尝试开发 draw() 方法时遇到问题(有来自 main 的调用)。 main 首先创建 9 张图,然后将它们全部绘制出来。当 draw() 被调用时,一个 NullPointerException 被抛出:

DrawingPanel dp = new DrawingPanel(canvasI.getWidth(), canvasI.getHeight())

为什么?如果您需要更多详细信息,请告诉我

private ArrayList<Shape> allShapes;
private ArrayList<DrawInstruction> allDrawInstructions;
private CanvasInstruction canvasI;
private DrawInstruction drawI;

public Drawing(ShapeLibrary shapeLib, File oneShape) throws FileNotFoundException{
try{
allDrawInstructions = new ArrayList<DrawInstruction>();
Scanner in = new Scanner(oneShape);
CanvasInstruction canvasI = CanvasInstruction.readFromFile(in);
while(in.hasNextLine()){
DrawInstruction drawInstruction = DrawInstruction.readFromFile(in);
allDrawInstructions.add(drawI);
}
} catch(FileNotFoundException e){
throw new FileNotFoundException("File doesn't exist");
}
}


public void draw(){
DrawingPanel dp = new DrawingPanel(canvasI.getWidth(),
canvasI.getHeight());
}

最佳答案

CanvasInstruction canvasI = CanvasInstruction.readFromFile(in); 行的局部变量隐藏在构造函数中private CanvasInstruction canvasI 字段。更改代码如下:-

public Drawing(ShapeLibrary shapeLib, File oneShape) throws FileNotFoundException {
//...
Scanner in = new Scanner(oneShape);
this.canvasI = CanvasInstruction.readFromFile(in);
//...
}

关于java - 抛出 NullPointerException,但对象已创建并正确返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com