首页 文章

java.lang.NullPointerException从文件读取并写入结构[重复]

提问于
浏览
-1

这个问题在这里已有答案:

旧的问题多次搜索,但我仍然不明白我做错了什么xD,这是我的代码:`

package dev.codenmore.tilegame.worlds;

import dev.codenmore.tilegame.Utils;
import dev.codenmore.tilegame.objects.Objects;

import java.awt.*;



public class World {

public class Object {

    private int id = 0,
                x = 0,
                y = 0;
    public Object(){

    }

    public void setId(int id) {
        this.id = id;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

private int width, height;
private int spawnX, spawnY;
private int x, y, id, nr = 0;
private Object[] objects;

public World(String path){
    loadWorld(path);
}

public void tick(){

}

public void render(Graphics g){
    int i = 0;
    for(; i <(width*height)/3; i++){
        getObject(i).render(g, objects[i].x, objects[i].y);

    }
}

public Objects getObject(int i){
    Objects o = Objects.objects[objects[i].id];
    if(o == null)
        return Objects.alpha;
    return o;
}

private void loadWorld(String path){
    String file = Utils.loadFileAsString(path);
    String[] tokens = file.split("\\s+");
    width = Utils.parseInt(tokens[0]);
    height = Utils.parseInt(tokens[1]);
    spawnX = Utils.parseInt(tokens[2]);
    spawnY = Utils.parseInt(tokens[3]);
    objects = new Object[width*height/3];

    for(int i = 4; i < width*height+3; i += 3){
        id = Utils.parseInt(tokens[i]);
        x = Utils.parseInt(tokens[i+1]);
        y = Utils.parseInt(tokens[i+2]);

        objects[nr].setId(id);
        objects[nr].setX(x);
        objects[nr].setY(y);
        nr++;
    }

}

}

`当我试图将数据写入我的结构时,错误发生在第64行,这告诉我正在尝试写入空内存,但我不知道如何自己处理这个 . 除此之外我还有第二个问题,这是最好的方法吗?我的意思是读取文件和写入数据到这里是我的文件:

6 3
960 540
0 0 0 255 0 0
2 0 500 2 1620 500
1 0 790 255 0 0

1 回答

  • 0

    好吧,isn 't it because id, x, y in Object are private, and you do not have setters in this class? therefore you don' t可以访问这些字段 . 我尝试在Object类中添加setter,然后使用 objects[nr].setId(id); 而不是 objects[nr].id = id;

相关问题