Search code examples
javanullpointerexceptiontile

Tile Map Loading Issues


In the Platformer I am making I need to load tiles in order to be able to create levels, but in the code below I seem to be having problems. It says that I have an error at this part:

String[] skips = skip.split(" ");

but it seems fine to me, and it's always worked before. Can somebody maybe give me some insight as to why this is not working?

Dungeon.java

package ScreenContents;

import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Dungeon {


private static int width;
private static int height;
private static final int tileSize = 32;
private int[][] map;

public void readMap(String location){
    URL url = getClass().getResource(location);
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

        width = Integer.parseInt(reader.readLine());
        height = Integer.parseInt(reader.readLine());
        map = new int[height][width];

        for (int y = 0; y < height; y++){
            String skip = reader.readLine();
            String[] skips = skip.split(" ");
            for (int x = 0; x < width; x++){
                map[y][x] = Integer.parseInt(skips[x]);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void renderMap(Graphics g){
    for (int y = 0; y < height; y++){
        for (int x = 0; x < width; x++){
            int newMapPos = map[y][x];

            if (newMapPos == 0){
                g.setColor(Color.black);
            }

            if  (newMapPos == 1){
                g.setColor(Color.white);
            }

            g.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);

        }
    }
}

}

Solution

  • The line: String[] skips = skip.split(" "); has skip set to null.

    This is because reader.readLine(); returned null.

    Looking at the documentation "A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached".

    You are basically reading too many lines from your file, which means the height in your file does not match the number of lines that are actually in the file.