我正在制作一款游戏。它不会在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
答案 0 :(得分:1)
通过查看可能为null的各个值开始调试。您可以使用此块作为示例:
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());
一旦确定了什么是null,就可以开始对代码进行反向跟踪,以确定为什么没有一个值设置在你期望的值。
答案 1 :(得分:1)
多么奇怪的编程...
然而,问题似乎就在这里:
1)在课程Game
中,您有一个名为 blocks 的HashMap<Block, Coordinates>
类型的静态字段。您正在将键的类Block
的实例插入到该映射中。对应的行是:
blocks.put(new Block(new BlockRectangle(rectID)), new Coordinates(rectx, recty));
2)同时在同一行中创建类型为BlockRectangle
的实例时,构造函数将构造中的对象作为键放入HashMap<Integer, BlockRectangle>
类型的静态字段中,名为 rects < / em>的。对应的行是:
rects.put(id, this);
3)然后你试图通过调用
获得一个Blockblocks.get(BlockRectangle.getByID(rectID))
内部表达式BlockRectangle.getByID(rectID)
将返回在地图 rects 中查找的BlockRectangle
实例。现在使用此实例在地图 blocks 中进行查找,但这仅将Block
存储为键,而不是BlockRectangle
s(请参阅第1点)。
在equals
和hashCode
中没有任何Block
(和BlockRectangle
)方法,您就没有进一步了解。但是在任何这些类中实现这些方法会使情况变得更糟,因为将块与块矩形进行比较并不是一个好主意。
您应该对软件进行全面的重新设计。
答案 2 :(得分:0)
空指针异常是代码尝试使用值执行某些操作的位置,但该值为null。值通常为null,因为它没有实例化Object o = new Object
,或者您从数据源中提取,其中所需的记录不存在,它将返回null。见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 0
中的唯一记录的ID为200
,您的地图会返回什么内容?
话虽如此,我不认为保留所有BlockRectangles的地图是最好的程序设计。相反,请考虑在主类中使用一个跟踪所有内容的变量。
PS。你的英语非常好,而且知道你在年轻时就开始编程是令人兴奋的!此外,由于您正在制作游戏,我想指出Game Development Stack Exchange网站,您可以在其中提出游戏特定问题,例如游戏设计或游戏制作者可能会更深入了解的编程问题。
答案 3 :(得分:0)
无论您在何处运行,您的代码都会抛出NullPointerException。只是在线程的run
方法中抛出此异常只能以两种方式捕获:通过使用try {...} catch(NullPointerException e) {...}
显式捕获它或者定义线程的uncaughtExceptionHandler()
。 / p>
run
方法我不一定是您的run
,而是定义为调用绘制渲染的方法。
根据您期望的RuntimeExceptions,您可以定义此类异常处理程序,也可以消除异常原因。在您的情况下,其中一个get
方法找不到元素并返回null。