将对象传入数组列表时,如何获得空指针异常?

时间:2019-03-14 23:25:40

标签: java nullpointerexception

背景

万岁! Pi DAYYY!我想做的是在屏幕上放置随机点。 gui在屏幕状态0中打开,当我按1时,屏幕状态更改为屏幕状态1,然后理论上应该在屏幕上添加随机点。但是,它不起作用。

问题

因此,如果您查看“ dotz.add(new Dot());”行,编译器将其标记为nullpointer异常,但我不确定为什么会这样,因为我正在传递Dot对象

此处的主控制器代码

package piday;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.util.ArrayList;

import com.sun.glass.events.KeyEvent;

public class controllah extends GameDriverV4 {
    int state = 0;
    Font font = new Font("Helvetica Neue", Font.BOLD,50);
    Dot Dot = new Dot();
    ArrayList<Dot> dotz;
    int time = 0;
    int delay = 50000;
    public controllah() {

    }

    public static void main(String[] args) {
        controllah h = new controllah();
        h.start();
    }


    public void draw(Graphics2D win) {
        if (state == 0) {
            win.setColor(Color.BLACK);
            win.drawString("'MONTE CARLO'", 10, 200);
            win.drawString("'PRESS 1'", 10, 200+font.getSize()+10);
            if (GameDriverV4.Keys[KeyEvent.VK_1]) {
                state = 1;
            }
            win.drawString("'Needle Thing'", 10, 200+font.getSize()+10+50);
            win.drawString("'PRESS 2'", 10, 200+font.getSize()+10+50+15);
            if(GameDriverV4.Keys[KeyEvent.VK_2]) {
                state = 2;
            }
        }


        if (state == 1) {
            /*
            if (time>delay) {

                time = 0;
            }
            else {
                time ++;
            }
            */

            dotz.add(new Dot());
            for (int i = 0; i<dotz.size()-1; i++) {
                dotz.get(i).draw(win);
            }

        }

        if (state == 2) {

        }

    }
}

此处没有目标代码-

package piday;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Random;

public class Dot {
    Color incolor = Color.BLACK;
    Color outcolor = Color.BLUE;
    boolean in = true;
    int x;
    int y;
    public Dot() {
        Random rand = new Random();
        this.x = rand.nextInt(800);
        this.y = rand.nextInt(800);
    }


    public void draw(Graphics2D g) {
        if (in) {
            g.setColor(incolor);
        }
        else {
            g.setColor(outcolor);
        }

        g.fillRect(x-1, y-1, 3, 3);

    }

}

我认为,由于我一直在尝试向数组列表“ dotz”中添加新的“ Dot”对象,因此,因为新的“ Dot”不是空对象,这会很好

0 个答案:

没有答案