I'm trying to read this text file and render the corresponding tiles on the screen.
The code for reading the map is as follows:
private void loadMap(InputStream is) throws IOException {
ArrayList lines = new ArrayList();
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?
Answer
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);
}
No comments:
Post a Comment