简体   繁体   中英

How to use unicode escape sequence with variables?

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;

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.

The value of letterNum is 49 (61 in octal), so it turns into "\\u49\u0026quot; , 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\u0026quot; + something .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM