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;
TCob
  • 21
  • 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. – Andrei Nikolaenko Feb 21 '15 at 20:39

2 Answers2

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.

Steve McKay
  • 2,123
  • 17
  • 26
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).

Bubletan
  • 3,833
  • 6
  • 25
  • 33