Printing Unicode Characters in Java - PrintWriter

1k views Asked by At

I am developing a card game in Java and I am currently using a command line to interact and display outputs of the game. I have been representing each card suit with A letter (H - Hearts, S - Spades etc.)

I came up with the idea of using the Unicode values rather than letters to show each suit

public String toSymbol(Suit suit){
    switch(suit){
        case SPADE:
            return "\u2664";
        case DIAMOND:
            return "\u2662";
        case CLUB:
            return "\u2667";
        case HEART:
            return "\u2661";
        default:
            return "null";
    }
}

My issue is that when trying to print these symbols they simply display our favourite Unknown Character '?'. I read that this could be due to the byte stream System.out.println() uses something too short? Instead I should use a Print Writer.

I tried this and still no results. Could it be to do with the format my commandline uses?

1

There are 1 answers

0
Basil Bourque On

Glyph

As commented, you should check that your System.out and console are set to UTF-8, and that a font is available containing glyphs for those characters.

You neglected to mention your operating system, but I’ll guess it is Microsoft Windows. If so, this Question might help: Java, UTF-8, and Windows console.

We can simplify your code. Java source code supports UTF-8, so you can use the actual suit characters directly rather then use the Unicode code point escapes.

Here are the four French-suited characters, in “black” and in “white”.

System.out.println( "♠️♥️♣️♦️" ) ; 
System.out.println( "♤♡♧♢" ) ; 

See this code run successfully at Ideone.com.

Enum

By the way, you can embed knowledge of the emoji character within your enum. No need to maintain this separate method as shown in your Question.

enum Suit {
    SPADES( "♠️" , "♤" ), HEARTS( "♥️" , "♡" ), CLUBS( "♣️" , "♧" ), DIAMONDS( "♦️" , "♢" );
    private final String emojiBlack, emojiWhite ;
    Suit( String emojiBlack , String emojiWhite ) {  // Constructor.
        this.emojiBlack = emojiBlack ;
        this.emojiWhite= emojiWhite ;
    }
    String emojiBlack() {  // Accessor (getter).
        return this.emojiBlack ;
    }
    String emojiWhite() {  // Accessor (getter).
        return this.emojiWhite ;
    }
}

Usage:

System.out.println(
    Suit.HEARTS.emojiBlack() 
);

♥️