-1

the old problem searched many times but i still do not understand what i am doing wrong xD, this is my code: `

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++;
    }

}

}

` the error occurs on line 64 when im trying to write data to my structure, which is telling me that am trying to write to empty memory but i dont know how to handle this on my own. Additional to that i have second question, is this the best way to do this ? i mean reading file and writing data to structure here is my file:

6 3
960 540
0 0 0 255 0 0
2 0 500 2 1620 500
1 0 790 255 0 0
  • ok so i manage to solve this my problem was that i didnt init all you hav to do is add one line: objects[nr] = new Object(); before writing anithing to that object – Kacper Lechowicz Dec 08 '17 at 09:47

1 Answers1

0

well, isn't it because id, x, y in Object are private, and you do not have setters in this class? therefore you don't have access to those fields. I'd try to add setters in Object class and then instead of objects[nr].id = id; use objects[nr].setId(id);

AlminaS
  • 95
  • 5