We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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
String
+
"anything" results another String in Java!That is so b/c the
+
binary operator is overloaded for both addition & concatenation operations:http://processing.org/reference/addition.html
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--
edit: late : )
The
+
operator is doing the conversion for you, you can use Processing'sstr()
to it by yourself: