characters and strings

edited July 2015 in JavaScript Mode

This works fine in java mode, but not in js mode. How can I convert the characters' unicode values back to the actual letters/numbers?

String theLetters = "Hello!";

void setup()
{
  size(400, 400);
}

void draw()
{
  translate(10, height/2);
  for (int i = 0; i < theLetters.length(); i++)
  {
    char thisLetter = theLetters.charAt(i);

    text(thisLetter, 0, 0);
    translate(textWidth(thisLetter), 0);
  }
}

void keyPressed()
{
  if (key != CODED) theLetters += key;
}
Tagged:

Answers

  • edited July 2015 Answer ✓

    Notice that p5.js isn't the same as "JS Mode". Which relies on pjs framework to transpile Java to JS syntax!
    Thus you've posted in the wrong category. Fixed it for ya!

    JavaScript doesn't have any match datatype for Java's char, which is actually a number type:
    http://ProcessingJS.org/reference/char/

    In Java, when we concatenate a String + char, the latter behaves as a String automatically.
    But not in JS, which still behaves as a number! :-SS
    That's why theLetters += key; have diff. results when running in Java or in JS.

    In order to fix that, we can coerce key to become a String before being concatenated w/ theLetters using str(): theLetters += str(key);:
    http://ProcessingJS.org/reference/str_/

    Even better, Java doesn't care whether we convert a char into String before a concatenation! O:-)

  • edited July 2015

    pow(Thanks, 2);

Sign In or Register to comment.