简体   繁体   中英

NullPointerException Error: How do I fix this one?

I am trying to make a simple image of four tic-tac-toe boards through a Java graphics program. My program compiles and can run, but does not produce the images of the four boards. I get this error in my Interactions Pane (I use DrJava to code):

Welcome to DrJava.  Working directory is C:\Users\Daniel\Desktop\CS Programs
> run TicTacToeBoards
java.lang.NullPointerException
    at TicTacToeBoards.drawTicTacToeBoard(TicTacToeBoards.java:38)
    at TicTacToeBoards.<init>(TicTacToeBoards.java:18)
    at TicTacToeBoards.main(TicTacToeBoards.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

This is the program I am attempting to run:

import java.awt.Color;

public class TicTacToeBoards {

  private NsccWindow win;

  public TicTacToeBoards() {

    NsccWindow win;
    win = new NsccWindow(10, 10, 330, 300);
    win.setTitle("Tic-Tac-Toe Boards");
    drawTicTacToeBoard(40, 40);
    drawTicTacToeBoard(40, 170);
    drawTicTacToeBoard(170, 40);
    drawTicTacToeBoard(170, 170);

  }  

  public void drawTicTacToeBoard(int x, int y) {

    NsccLine vertLineL;
    NsccLine vertLineR;
    NsccLine horizLineU;
    NsccLine horizLineD;

    vertLineL = new NsccLine((x + 30), y, (x + 30), (y + 90));
    vertLineR = new NsccLine((x + 60), y, (x + 60), (y + 90));
    horizLineU = new NsccLine(x, (y + 30), (x + 90), (y + 30));
    horizLineD = new NsccLine(x, (y + 60), (x + 90), (y + 30));


    win.add(vertLineL);
    win.add(vertLineR);
    win.add(horizLineU);
    win.add(horizLineD);


    win.repaint();




  }

  public static void main(String[] args) {
    TicTacToeBoards test = new
    TicTacToeBoards();
  }
}

I am fairly new to Java programming and I have been stuck on trying to find the error through debugging in DrJava with no avail. Can someone help? :)

Remove this line from the constructor:

NsccWindow win;

You already have win field, so there's no need to declare it inside the constructor too.

When you declare it inside the constructor, you hide the instance field and instantiate the variable that is limited to the constructor scope only. So when you try to access the instance field inside drawTicTacToeBoard , it is actually null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM