Search code examples
javaescapingjava.util.scannerjava-io

Scanner difficulties with different escape characters


First off let me start by saying that I know I'm not the only one who has experienced this issue and I spent the last couple of hours to research how to fix it. Sadly, I can't get my scanner to work. I'm new to java so I don't understand more complicated explanations that some answers have in different questions.

Here is a rundown: I'm trying to read out of a file which contains escape characters of cards. Here is a short version: (Numbers 2 and 3 of 4 different card faces)

\u26602,2 
\u26652,2 
\u26662,2 
\u26632,2 
\u26603,3 
\u26653,3 
\u26663,3
\u26633,3

This is the format: (suit)(face),(value). an example:

  • \u2663 = suit
  • 3 = face
  • 3 = value

This is the code I'm using for reading it:

File file = new File("Cards.txt");
try {
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        String[] temp = line.split(",");
        cards.add(new Card(temp[0], Integer.parseInt(temp[1])));
    }
    scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

the ArrayList cards should have 52 cards after this containing a name (suit and face) and a value. When i try to print the name this is the output:

\u26633

While it should be:

♣3

Can anyone give me pointers towards a solution? I really need this issue resolved. I don't want you to write my code for me.

Thanks in advance


Solution

  • Simply store directly the suit characters into your files Cards.txt using UTF-8 as character encoding instead of the corresponding unicode character format that is only understood by java such that when it is read from your file it is read as the String "\u2660" not as the corresponding unicode character.

    Its content would then be something like:

    ♠2,2
    ...
    

    Another way could be to use StringEscapeUtils.unescapeJava(String input) to unescape your unicode character.

    The code change would then be:

    cards.add(new Card(StringEscapeUtils.unescapeJava(temp[0]), Integer.parseInt(temp[1])));