Reputation: 1305
I'm writing a simple level creator based on characters in a text file. It's not really a problem at all, but I was wondering why I have to check for the ASCII value of '1' rather than the char '1' in order to return true, while the earlier usage of the char works fine.
Here is the code :
package com.side.side;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LevelGenerator {
public LevelGenerator() throws IOException{
char[][] map = new char[4][4];
int i = 0;
int j = 0;
String thisLine;
BufferedReader reader = new BufferedReader(new FileReader("C:/Users/Downloads/Desktop/eclipse/level.txt"));
while((thisLine = reader.readLine()) != null){
while(i < thisLine.length()){
map[j][i] = thisLine.charAt(i);
i++;
}
if(i==thisLine.length()){
j+=1;
i = 0;
}
System.out.println(thisLine);
}
String maplis = Arrays.deepToString(map);
System.out.println(maplis);
for(int x = 0;x<=3;x++){
for(int y = 3;y>=0;y--){
if (map[y][x] == 1){System.out.println("true");}
else{System.out.println("false");}
}
}
}
}
Upvotes: 0
Views: 116
Reputation: 50042
The Java char
type is a duality. It's an integer type with a range of 0 to 65535. When printed or used in string contexts the numeric value is taken as the UTF-16 code for a character. This expression:
if (map[y][x] == 1)
is comparing the character code number against the integer 1. (Character 1 is an obscure and obsolete control character -- not what you want in this case.) Use a character literal (single quotes):
if (map[y][x] == '1')
..and that will compare against the actual printable/typeable character "1". Or technically it's still comparing code numbers, but now it's using the right number. The above is the same as:
if (map[y][x] == 49)
Upvotes: 1