Rich Steinmetz
Rich Steinmetz

Reputation: 1281

Concatenate String to unicode in java

public class TruthTableValue {
    private boolean truthValue;
    private String name = "";

    private int unicodeStartNameValue = 41; /*
    * we want our String always to start with A and then go up the alphabet.
    * this can be done using the unicode 16.
    */

    public TruthTableValue() {
        truthValue = true;
        name += "\u00" + Character.toString((char)unicodeStartNameValue);
        unicodeStartNameValue++;
    }

    public String getName() {
        return name;
    }
}

In this code I try to have an object which creates after every generation an object with a name which is equal to the unicode "\u00" + "41" or "42" or "43" and so on (A, B, C and so on). My problem is that "\u00" is in accordance with the compiler not a "valid unicode", so that it doesn't compile properly and it's not possible to execute it neither.

How do I get rid of the compile error or how do I solve this problem in general?

Thanks in advance!

Upvotes: 0

Views: 2748

Answers (1)

ajb
ajb

Reputation: 31689

"\u0041" in a Java program is processed by the compiler, not at run time. If the Java compiler sees this in a program, it will treat it as the string "A". (That's why you're getting an error; the compiler doesn't know what to do if \u isn't followed by four hex digits.)

If you want something that converts the 6-character string "\\u0041" to "A" at run time, you'll need to find a library method for that. I don't know of one, and it's the hard way to do it anyway. In Java, a char is already a number. So if you say

private char unicodeStartNameValue = 0x41;

instead of

private int unicodeStartNameValue = 41;

and keep adding 1 to the char, you'll have the characters you want, and you can convert them to strings with Character.toString(charValue), which would return a 1-character string. (If you just say 41, that's a decimal number, and first character would be ')', not 'A'.)

Your idea wouldn't work, anyway, because you wouldn't be able to get "\u004a". If you were keeping a decimal number and trying to append it to "\u00", your sequence would be A, B, C, D, E, F, G, H, I, P, Q, R, ..., since it would jump from "\u0049" to "\u0050".

Upvotes: 2

Related Questions