【问题标题】:Getting NullPointerException while creating a game创建游戏时出现 NullPointerException
【发布时间】:2013-09-16 13:21:59
【问题描述】:

我正在创建一个游戏。它不会在 Eclipse 中引发错误,但是当我在调试模式下运行它时,它会在以下行引发 NullPointerException

System.out.println("Stone x: " + blocks.get(BlockRectangle.getByID(rectID)).getX() + " y: " + blocks.get(BlockRectangle.getByID(rectID)).getY());

Game.java:

package lt.projecturanium;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.util.HashMap;

import javax.swing.JFrame;

import lt.projecturanium.blocks.Block;
import lt.projecturanium.blocks.BlockRectangle;
import lt.projecturanium.entity.Player;
@SuppressWarnings("unused")

public class Game extends Canvas implements Runnable{

    private static final long serialVersionUID = 1L;

    private static JFrame _frame;
    public static Game _instance;

    private static final String TITLE = "Project Uranium";
    private static final int WIDTH = 650;
    private static final int HEIGHT = WIDTH * 3 / 4;

    private static final int UPDATE_RATE = 50;
    private static final int RENDER_RATE = 100;

    public static HashMap<Block, Coordinates> blocks = new HashMap<Block, Coordinates>();

    public int rectx = 0;
    public int recty = 0;
    public int rectID = 0;

    public boolean hitted = false;

    public float interpolation;

    public static final Dimension SIZE = new Dimension(WIDTH, HEIGHT);

    private Thread _thread;

    private boolean _running;

    private int _totalTicks = 0;
    private int _tps = 0;
    private int _fps = 0;

    public Game()
    {
        _instance = this;
        setPreferredSize(SIZE);
        setMinimumSize(SIZE);
        setMaximumSize(SIZE);

        _frame = new JFrame(TITLE);

        _frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        _frame.setLayout(new BorderLayout());
        _frame.add(_instance, BorderLayout.CENTER);
        _frame.pack();

        _frame.setResizable(false);
        _frame.setLocationRelativeTo(null);
        _frame.setVisible(true);
        createBufferStrategy(2);
        blocks.put(new Block(new BlockRectangle(200)), new Coordinates(30, 50));
    }
    public synchronized void start()
    {
        _running = true;
        _thread = new Thread(this, TITLE+"_main");
        _thread.start();
    }
    public synchronized void stop()
    {
        _running = false;
        if (_thread != null)
        {
            try {
                _thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void paint(Graphics g) {
        super.paint(g);  // fixes the immediate problem.
        Graphics2D g2 = (Graphics2D) g;
        g2.drawString("FPS: " + _fps + "\n TPS: " + _tps, 10, 10);
        if (hitted)
        {
            recty = 0;
            rectx += 21;
            rectID++;
            blocks.put(new Block(new BlockRectangle(rectID)), new Coordinates(rectx, recty));
            hitted = false;
        }
        recty++;
        g2.drawImage(Player.getTexture(), 60, 60, null);
        g2.drawRect(rectx, recty, 20, 20);
        g2.setColor(new Color(101, 67, 33));
        g2.fillRect(0, 430, getWidth(), getHeight());
        g2.setColor(new Color(0, 100, 0));
        g2.fillRect(0, 420, getWidth(), 10);
        g2.setColor(Color.BLACK);
        if (recty == (419 - 20))
        {   
            hitted = true;
        }
    }
    public void run() {
        double lastUpdateTime = System.nanoTime();
        double lastRenderTime = lastUpdateTime;
        final int ns = 1000000000;
        final double nsPerUpdate = (double) ns / UPDATE_RATE;
        final double nsPerRender = (double) ns / RENDER_RATE;
        final int maxUpdatesBeforeRender = 5;

        int lastSecond = (int) (lastUpdateTime / ns);
        int tickCount = 0;
        int renderCount = 0;
        while (_running) {

          long currTime = System.nanoTime();
          int tps = 0;

          while ((currTime - lastUpdateTime) > nsPerUpdate && tps < maxUpdatesBeforeRender) {
            update();
            tickCount++;
            _totalTicks++;
            tps++;
            lastUpdateTime += nsPerUpdate;
            interpolation = Math.min(1.0F, (float) ((currTime - lastUpdateTime) / nsPerUpdate));
            render(interpolation, getGraphics());
          }

          if (currTime - lastUpdateTime > nsPerUpdate) {
            lastUpdateTime = currTime - nsPerUpdate;
          }
          if (currTime - lastRenderTime == maxUpdatesBeforeRender + 1)
          {
              render(interpolation, getGraphics());
          }
          renderCount++;
          lastRenderTime = currTime;

          int currSecond = (int) (lastUpdateTime / ns);
          if (currSecond > lastSecond) {
            _tps = tickCount;
            _fps = renderCount;
            tickCount = 0;
            renderCount = 0;
            lastSecond = currSecond;
            _frame.setTitle(TITLE + " | TPS: " + _tps + " | FPS: "+ _fps);

          }

          while (currTime - lastRenderTime < nsPerRender && currTime - lastUpdateTime < nsPerUpdate) {
            Thread.yield();
            try {
              Thread.sleep(1);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            currTime = System.nanoTime();
          }
        }   
      }
    public void update()
    {
        _frame.pack();
    }
    public void render(float interp, Graphics g)
    {
        BufferStrategy myStrategy = getBufferStrategy(); 
        Graphics gra = myStrategy.getDrawGraphics();
        paint(gra);
        g.dispose();
        myStrategy.show();
        //System.out.println("Grass x: " + blocks.get("grass").getX() + " y: " + blocks.get("grass").getY());
        System.out.println("Stone x: " + blocks.get(BlockRectangle.getByID(rectID)).getX() + " y: " + blocks.get(BlockRectangle.getByID(rectID)).getY());
    }
}

BlockRectangle.java:

package lt.projecturanium.blocks;

import java.awt.Image;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;

import lt.projecturanium.Game;

public class BlockRectangle extends Block{
    private int id;
    private static HashMap<Integer, BlockRectangle> rects = new HashMap<Integer, BlockRectangle>();
    public BlockRectangle(int id)
    {
        super();
        this.id = id;
        rects.put(id, this);
    }
    public int getID()
    {
        return this.id;
    }
    public static BlockRectangle getByID(int id)
    {
        return rects.get(id);
    }
    public static Image getTexture()
    {
        try{        
            return ImageIO.read(Game._instance.getClass().getClassLoader().getResource("../res/player.png"));   
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

Block.java:

包 lt.projecturanium.blocks;

public class Block {
    private Block block;
    public Block (Block block){
        this.block = block;
    }
    public Block getBlock() {
        return block;
    }
    public Block getBlockById(int id)
    {
        return block;
    }
    public Block()
    {

    }
}

错误:

Thread [Project Uranium_main] (Suspended (exception NullPointerException))  
    Game.render(float, Graphics) line: 186  
    Game.run() line: 139    
    Thread.run() line: not available    

【问题讨论】:

  • 能否将错误输出添加到问题中?
  • I think you know that i'm creating a game. -- 目前不知道,但会记录下来。
  • “它不会在 Eclipse 中引发错误”是什么意思?你的意思是Eclipse不报编译错误?您是在 Eclipse 中调试它,对吧?
  • 是的,我们可以使用堆栈跟踪。
  • 它不会在 Eclipse 中引发错误,因为这是运行时错误,而不是编译时错误。该代码在编译时语法上是正确的,但是当它运行时,某处会出现逻辑错误。此特定错误意味着该行中的一项是 null 并且无法使用。它可能是变量blocks(或者,更可能的是,无论blocks 上的.get() 方法返回什么),但我不能从这里确定。您似乎在为变量分配任何内容之前尝试使用它。

标签: java


【解决方案1】:

通过查看可能为空的单个值开始调试。您可以使用此块作为示例:

BlockRectangle blockRectangle = BlockRectangle.getByID(rectID);
System.out.println("BlockRectangle: " + blockRectangle);
Coordinates coordinates= blocks.get(blockRectangle);
System.out.println("Coordinates: " + coordinates);
System.out.println("X: " + coordinates.getX());
System.out.println("Y: " + coordinates.getY());

一旦您确定什么是空值,您就可以开始回溯您的代码,以确定为什么没有设置您期望的值。

【讨论】:

  • 我确定是坐标。
  • 这是一个很好的第一步——现在您知道当您调用 blocks.get(blockRectangle) 时,您会得到一个空值。由于您使用的是 HashMap,因此有两个可能的原因会导致 null:key (blockRectangle) 不存在,或者 key 存在,但被分配了 null 值。您可以通过遍历 Map 并打印其中包含的内容来确定这一点。您还需要查看将值分配到块 HashMap 的位置,以确保 1) 在某个时候实际调用代码,2) 如果不应该插入 null 值。
【解决方案2】:

多么奇怪的编程......

但是,问题似乎就在这里:

1) 在Game 类中,您有一个HashMap&lt;Block, Coordinates&gt; 类型的静态字段,称为blocks。您正在为该映射中的键插入类 Block 的实例。对应的行是:

blocks.put(new Block(new BlockRectangle(rectID)), new Coordinates(rectx, recty));

2) 在同一行中创建BlockRectangle 类型的实例的同时,构造函数将构造中的对象作为键放入名为rectsHashMap&lt;Integer, BlockRectangle&gt; 类型的静态字段中。对应的行是:

rects.put(id, this);

3) 然后你试图通过调用来获得一个块

blocks.get(BlockRectangle.getByID(rectID))

内部表达式BlockRectangle.getByID(rectID) 将返回在地图rects 中查找的BlockRectangle 实例。有了这个实例,现在在地图 blocks 中进行了查找,但这只会将 Blocks 存储为键,而不是 BlockRectangles(参见第 1 点)。

如果在BlockBlockRectangle 中没有任何equals(和hashCode)方法,您将不会有任何进展。但是在这些类中实现这些方法会使情况变得更糟,因为将块与块矩形进行比较并不是一个好主意。

您应该彻底重新设计您的软件。

【讨论】:

  • 好的,我把BlockRectangle中的HashMap改成了HashMap,但是什么都没变..
  • 将 BlockRectangle 中的映射更改为 HashMap 不会更改任何内容,因为您仍将 BlockRectangle 实例作为值存储在此映射中。也许您可以将另一个映射更改为 HashMap,然后您不应该创建包装 BlockRectangle 的“new Block(...)”,而只需使用新创建的 BlockRectangle 作为键。我不知道,如果这行得通。也许您认识某个人,他可以与您一起进行认真的重新设计。
【解决方案3】:

无论您在何处运行,您的代码都会引发 NullPointerException。只是在线程的run 方法中抛出这个异常只能通过两种方式捕获:要么通过try {...} catch(NullPointerException e) {...} 显式捕获,要么通过定义线程的uncaughtExceptionHandler()

run 方法我不一定是您的run,而是定义为调用绘制渲染的方法。

根据您期望的 RuntimeExceptions,您可以定义这样的异常处理程序,也可以消除异常的原因。在您的情况下,get 方法之一找不到元素并返回 null。

【讨论】:

    【解决方案4】:

    空指针异常是您的代码尝试对某个值执行某些操作,但该值为空。一个值通常为空值,因为要么它没有实例化Object o = new Object,要么你从数据源中提取所需的记录不存在,它将返回空值。见http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html

    在您的情况下,您在 System.out.println("Stone x: " + blocks.get(BlockRectangle.getByID(rectID)).getX() + " y: " + blocks.get(BlockRectangle.getByID(rectID)).getY()); 行中获得了 NPE,因为 Map 返回了一个空 BlockRectangle 对象。

    关于您对@GamerJosh 的回答的评论,您的错误在坐标中,我猜这是因为您从getById() 返回了一个空BlockRectangle。可以这样想:您永远不会增加/更改您的 rectId 字段,而是将第一个对象添加为 ID 为200。除此之外,您在您的paint() 方法中添加ID 为0 的新块。但是,如果您在其他块出现在您的地图中之前到达此日志记录语句会发生什么?如果其中唯一记录的 ID 为 200,您的地图将返回 ID 0 什么?

    话虽如此,我不认为保留所有 BlockRectangle 的地图是最伟大的程序设计。相反,请考虑在您的主类中使用一个变量来跟踪所有这些。

    PS。你的英语很好,很高兴知道你在很小的时候就开始编程了!另外,由于您正在制作游戏,我想指出 Game Development Stack Exchange 网站,您可以在该网站上提出游戏特定问题,例如游戏设计或游戏开发者可能更深入了解的编程问题。

    【讨论】:

    • 好的,我会检查的 :) 谢谢你的回答 :)
    • 您的地图是静态的,但您的 BlockRectangle 类不是。
    • getByID() 类是静态的?
    • Emm,BlockRectangle 不为空:BlockRectangle: lt.projecturanium.blocks.BlockRectangle@15e538e
    • 如果您的 BlockRectangle 不为 null,则将 BlockRectangle 与坐标关联时会出现问题。要了解发生这种情况的原因,请查看@Seelenvirtuose 的回答。
    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2012-03-23
    • 1970-01-01
    • 2018-02-08
    • 2015-03-28
    相关资源
    最近更新 更多