简体   繁体   中英

Java HashMap returning null

I am getting things returned as null, everything is always set, and it works up to a point...

I dont understand why i'm getting this issue... please help,

Everything should be set, but I'm getting the chunk returned as null

package com.blazingkin.world;
import java.util.HashMap;
import java.util.Map;

import com.blazingkin.atrox.AtroxAdventrum;

public class World {

    public World(AtroxAdventrum aa){
        chunks = new HashMap<Integer,Map<Integer,Chunk>>();
    }



    public void setBlock(int x, int y, int newBlock){

    }

    public void setMetadata(int x, int y, int newMeta){

    }

    private void setChunk(int x, int y, Chunk c) {
        if(chunks.get(x) == null) {
            chunks.put(x, new HashMap<Integer, Chunk>());
            System.out.println("Created new chunk "+ x);
        }
        chunks.get(x).put(y, c);
        System.out.println("Set Chunk: "+x+", "+y);
    }
    private Chunk getChunk(int x, int y) {
        if(chunks.get(x) == null){
        Chunk c = new Chunk(y*64, x, y);
        setChunk(x, y, c);
        return c;
        }
        return chunks.get(x).get(y);
    }


    public int getChunkX(int x){
        return x/64 - x%64;
    }
    public int getChunkY(int y){
        return y/64 - y%64;
    }

    public int getBlock(int x, int y){
        return getChunk(getChunkX(x), getChunkY(y)).getBlock(x&64, y%64);
    }

    public int getMetadata(int x, int y){
        return 1;
    }



    Map<Integer,Map<Integer,Chunk>> chunks;

}

Error Message:

...

Created new chunk -23

Set Chunk: -23, 16


Exception in thread "main" java.lang.NullPointerException
    at com.blazingkin.world.World.getBlock(World.java:49)
    at com.blazingkin.render.ScreenOutput.render(ScreenOutput.java:30)
    at com.blazingkin.atrox.AtroxAdventrum.draw(AtroxAdventrum.java:34)
    at com.blazingkin.atrox.Core.gameLoop(Core.java:60)
    at com.blazingkin.atrox.Core.run(Core.java:27)
    at com.blazingkin.atrox.AtroxAdventrum.main(AtroxAdventrum.java:14)

You have a check that does this: if(chunks.get(x) == null){

But you never check about chunks.get(x).get(y) and if the get(y) is null! :-O

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM