Why when String ... keyIn=null; does keyIn= key; generate error "cannot convert char to String"?

edited September 2014 in Questions about Code

This code does what I want, but there are two odd things that I can not rationalize:

1) When keyIn is a String and null .. keyIn = key; generate an error message "cannot convert char to String" .. But keyIn = " " + key; works

2)Immediately trying to trim the lead space fails, but putting the trim command after the second character is entered works

I am writing because I want to use this in the future where I may try to input a string that starts with a space. And this will strip the space no matter what.

This code works and has the questions in the context of the code:

String keyIn = ""; 
void setup() {}
void draw() {}
void keyPressed() {
  if (key == RETURN || key == ENTER) {
      println(".."+keyIn);
      keyIn = null;
    } else {
      if (keyIn == null) {
           // keyIn = key; doesn't work .. generates message "cannot convert from char to String" ... why?
           keyIn = " " + key;
           // keyIn = trim(keyIn); doesn't work here .. but does work below ... why?
      } else {
           keyIn = keyIn + key;
           keyIn = trim(keyIn);//now this will clip any leading space someone tries to type in the future and look like a bug if this code is reused ... is there another solution?
      }
    }
}

Answers

  • edited September 2014 Answer ✓

    But keyIn = " " + key; works.

    String + "anything" results another String in Java!

    • String s = "" + key;
    • String s = key + "";
    • String s = str(key);

    That is so b/c the + binary operator is overloaded for both addition & concatenation operations:
    http://processing.org/reference/addition.html

    Immediately trying to trim() the lead space fails,...

    Function trim() accepts String or String[] parameters only:
    http://processing.org/reference/trim_.html

    Alternatively, we can use trim() method from String class:
    http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim--

  • _vk_vk
    edited September 2014

    edit: late : )

    The + operator is doing the conversion for you, you can use Processing's str() to it by yourself:

    String keyIn = ""; 
    void setup() {}
    void draw() {}
    void keyPressed() {
      if (key == RETURN || key == ENTER) {
          println(".."+keyIn);
          keyIn = null;
        } else {
          if (keyIn == null) {
               // keyIn = key; doesn't work .. generates message "cannot convert from char to String" ... why?
               keyIn =str(key);
               // keyIn = trim(keyIn); doesn't work here .. but does work below ... why?
          } else {
               keyIn += str(key);
          }
        }
    }
    
Sign In or Register to comment.