libinzhou
libinzhou

Reputation: 37

Java System.out.println after reading from HashMap

The following is my code:

public void serialize() throws IOException {
    if(this.DO.size()==0){
        return;
    }
    for(Map.Entry<SearchKey,Float>set:DO.entrySet()){
        SearchKey key = set.getKey();
        float dist = set.getValue();
        long code = key.mc;
        char level = key.level;
        System.out.println(code);
        System.out.println(level);
        System.out.println(dist);
    }

}

The dataset has 4 elements:

274672398340,10,561.53235
1125058143634206,13,68.06594
1125058143634189,13,18.427612
1125058143634204,13,86.49355

where the first entry is the key and the middle entry is the level and the last entry is the distance. When I used Intelijj debugger, I found code, level and dist actually have the right values, but when I use the print statement, I got the following:

274672398340


561.53235
1125058143634206

68.06594
1125058143634189

18.427612
1125058143634204

86.49355

Does anyone know what may cause this error? Thanks.

Upvotes: 0

Views: 56

Answers (1)

majusebetter
majusebetter

Reputation: 1592

The problem is char level = key.level;.

Since you have a char data type, System.out.println() prints a character instead of a number, i.e. the number is interpreted as ASCII code. ASCII code 10 is LINE FEED, code 13 is CARRIAGE RETURN - that's why you see those newlines.

Try to cast the char to int when printing:

System.out.print((int) level);

This should do the trick.

Upvotes: 1

Related Questions