1
\$\begingroup\$

I'm trying to read this text file and render the corresponding tiles on the screen.

trial map

The code for reading the map is as follows:

private void loadMap(InputStream is) throws IOException {
    ArrayList<String> lines = new ArrayList<String>();
    int width = 0;
    int height = 0;

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            reader.close();
            break;
        }

        if (!line.startsWith("!")) {
            lines.add(line);
            width = Math.max(width, line.length());
        }
    }
    height = lines.size();

    for (int j=0; j < 18; j++) {
        String line = (String) lines.get(j);
        for (int i=0; i < width; i++) {

            if (i < line.length()) {
                char ch = line.charAt(i);
                Tile t = new Tile(i, j, Character.getNumericValue(ch));
                tiles.add(t);
            }
        }
    }

}

The first problem I have is with Character.getNumericValue(ch) as this does not seem to be doing anything, resulting in a NullPointerException. When I remove it and replace it with either a 1 or a 2 I'm able to render the tiles onto the screen but somehow the spaces in between the digits are interpreted as tiles, resulting in a continuous block of tiles eg in the second line with 1s results in tiles beginning from the left margin up until the last 1. How can I fix this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If I have analyzed the problem correctly the issue here is that Character#getNumericValue(ch) is returning -1. This is because it is reading all characters in the line, including whitespace characters, which does not have a numeric value. The Character#getNumericValue(ch) javadocs read:

If the character does not have a numeric value, then -1 is returned.

The solution would be to do something like this inside of your for-loop where you create the tile:

// Inside of the for-loop...
if(i < line.length()) {
    char ch = line.charAt(i);
    int charValue = Character.getNumericValue(ch);

    // Checks if the character is an invalid character such as a whitespace.
    if (charValue == -1)
        continue;

    Tile t = new Tile(i, j, charValue);
    tiles.add(t);
}
\$\endgroup\$
1
  • \$\begingroup\$ wow! thanks! I struggled quite a lot with this. Eventually figured out that the blank spaces were the cause of the problem and I developed a workaround and was able to finish my project. This will come in handy in future projects :) \$\endgroup\$
    – Macharia
    Commented Aug 18, 2016 at 9:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .