0

This is the code I currently have to concatenate a then b then c and so on in a loop (scanned number of times) using java:

public String toString() { String answers = ""; int numChoices = choices.length; char letter; String result; int letterNum = 0061; while (numChoices > 0) { letter = "\u" + letterNum; result = letter + ") " + choices[choices.length-numChoices] + "\n"; answers += result; numChoices --; letterNum ++; } return question + "\n" + answers; } 

I thought unicode escape sequences would be my best option, but it didn't work the way I tried so I'm obviously doing something wrong. How do I fix this?

The error I'm getting is:

MultChoice.java:40: illegal unicode escape letter = "\u" + letterNum; 
1
  • 0061 is 49 which is ASCII for "1" and you seem to enumerate choices, why would you need escaping at all? Just use normal values 1, 2, 3 etc. Commented Feb 21, 2015 at 20:39

2 Answers 2

2

Unicode escapes are processed by javac, very early in compilation, before parsing. The compiler never sees Unicode escapes, only code points. Therefore you can't use them at runtime. Instead, try this:

public String toString() { String answers = ""; int numChoices = choices.length; char letter = 'a'; String result; while (numChoices > 0) { result = "" + letter + ") " + choices[choices.length-numChoices] + "\n"; answers += result; numChoices --; letter ++; } return question + "\n" + answers; } 

A char is just an unsigned 16-bit integer, so you can do all the normal integer things with it, like increment. There's no need for a separate int--'a' and (char) 0x61 are the same thing.

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

3 Comments

Thanks for the help. I had no idea this could work.
Now make it work with all Unicode code points, not merely the BMP.
Dealing with supplementary planes in Java is a pain. It's also out of scope for this question or answer.
0

The value of letterNum is 49 (61 in octal), so it turns into "\u49", which is not valid.

You possibly were supposed to use 0x0061, and then turn it to a String using Integer.toHexString(letterNum).

Edit: It seems that you can't create a String using "\u" + something.

So, a possible way is Character.toString((char) letterNum).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.