Loading...
Logo
Processing Forum
It's silly but I can't store numbers (0 to 9) from the keyboard. My idea is to use the keyboard to enter numbers into an algorithm. In other words, imagine a calculator sketch where the input is the keyboard. I thought about using this:

int variable;
void keyPressed(){
if(key==0){
variable=0;
}
...

..but it seems too excessive to setup an if statement for every number. I also tried this:

println(key);

but that results nothing. It's annoying...it must be easy to enter numbers from the keyboard but I couldn't figure out how... Thank for your help in advance!

Replies(5)

Check out the code below.
Copy code
  1. int variable;
  2. void keyPressed() {
  3.   variable = key-48;
  4.   println(variable);
  5. }

I don't get anything... I tried clicking in the window to get focus but still nothing. Weird.
Got it:

int variable;
void setup(){
}
void draw(){
}
void keyPressed() {
  variable = key-48;
  println(variable);
}


Thanks for the help!
Hi!
i want to do something like this, but i want to store more numbers not just 0 to 9. for example: i want to introduce a number in processing like 1200 or 1255 and compare this number with a sensor reading.
with your code if i introduce 1255 it prints
 
1
2
5
5
how can i do that?
That's a little bit more tricky:

Copy code
  1. int variable=0;
  2. void setup(){
  3. }
  4. void draw(){
  5. }
  6. void keyPressed() {
  7.   if( key >= '0' && key <= '9' ){
  8.     variable*=10;
  9.     variable+=key-48;
  10.   }
  11.   if( key == BACKSPACE || key == DELETE ){
  12.     variable/=10;
  13.   }
  14.   if( key == ENTER || key == RETURN ){
  15.     // Use value.
  16.     variable = 0;
  17.   }
  18.   println( variable );
  19. }