gpt4 book ai didi

java - 游戏显示空指针异常

转载 作者:行者123 更新时间:2023-11-30 04:02:41 24 4
gpt4 key购买 nike

我试图显示一个黑色窗口,但我在第 72 行和第 43 行不断收到空指针异常。这是我的视频游戏的基础,自从我刚接触 java 以来,我一直在使用教程来帮助我。它开始时是一个无法访问的代码错误,但我通过返回修复了该错误,然后这个问题立即出现了任何帮助吗?代码:

package com.tyler99b.platformer.window;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

public class Game extends Canvas implements Runnable
{

private static final long serialVersionUID = 506346024107270629L;

private boolean running = false;
private Thread thread;

public synchronized void start(){
if(running)
return;

running = true;
thread = new Thread(this);
thread.start();
}

public void run()
{
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
updates++;
delta--;
}
render();
frames++;

if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames + " TICKS: " + updates);
frames = 0;
updates = 0;
}
}

}

private void tick()
{

}

private void render()
{


BufferStrategy bs = this.getBufferStrategy();
if(bs == null);
{
this.createBufferStrategy(3);

}

Graphics g = bs.getDrawGraphics();

g.setColor(Color.black);
g.fillRect(0,0, getWidth(), getHeight());

g.dispose();
bs.show();


}

public static void main(String args[]){
new Window(800,600, "Platformer Prototype", new Game ());
}
}

最佳答案

看来您正在使用一种常见的模式来创建空值。但是,在这里您将 bs 设置为 getBufferStrategy(),如果它为 null,则创建它。假设该功能成功。 bs 仍然为空

BufferStrategy bs = this.getBufferStrategy(); 
if (bs == null){
this.createBufferStrategy(3);
//bs still null
}

您需要重新尝试将 bs 设置为等于某值

BufferStrategy bs = this.getBufferStrategy(); 
if (bs == null) {
this.createBufferStrategy(3);
bs = this.getBufferStrategy();
}

所有这些都假设 createBufferStrategy 不会失败。如果可以的话,您必须决定在这种情况下该怎么做

其他说明

你的 if 语句也有一个停留;在里面。这使它成为一个空的 if 语句

关于java - 游戏显示空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com