0

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.

3
  • 2
    What output do you expect? And why isn't each number on a separate line? Are you running the code in your question? Commented Jul 13, 2022 at 22:21
  • 2
    By the way, let me remind you that char/Character has been legacy since Java 5, essentially broken since Java 2. As a 16-bit type, char is physically incapable of representing most characters. I suggest defining your field with a different data type. Commented Jul 13, 2022 at 22:37
  • Hello thank you. Yes I ran the code. It was supposed to print out a total of 12 numbers each at a separate line. But here some numbers are missing. I feel the answer below helps. Also thank you Basil for this reminder. I actually did not know that. Commented Jul 14, 2022 at 1:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good catch, and a good Answer. An even better solution might be avoiding the use of the char as the type of key.level.
Thank you! The problem is solved. And I will try to switch to short now. I was too greedy to try to save this 1 byte between char and short because I know my level is at most 20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.