NullPointerException is thrown, but the object is created and correctly return values

I. KK. :

Working on a program that has a library of shapes saved in a folder and instruction files (the describe the specifics of the drawing). Ran into a problem when trying to develop the draw() method (has a call from the main). main first creates 9 drawings and then draws all of them. when draw() is called a NullPointerException is thrown about the :

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

why? if you need any more details, please let me know

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());
}
Awan Biru :

The local variable at line CanvasInstruction canvasI = CanvasInstruction.readFromFile(in); inside constructor hides private CanvasInstruction canvasI field. Change code as below:-

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142109&siteId=1