Keypressed(): Can this even be done?

Hi all,

I’ve been working on a project for a few days where I’m meant to use keypressed to do a number of things.

First thing I’m struggling with:

“Make a keyPressed function with the following behavior:
• The first time a sequence of numbers is entered (followed by a newline), treat it as an integer, and store it as the x coordinate of a target. The second time a sequence of numbers is entered (followed by a newline), treat it as an integer, and store it as the y coordinate of a target. Ignore all future integers that are entered.”

I’m stumped on how to check if the key is an integer.

I tried:
void keyPressed() {
if ((key == 1) || (key == 2) || (key == 3) || (key == 4) || (key == 5) || (key == 6)
|| (key == 7) || (key == 8) || (key == 9) || (key == 0)) || (key == ‘\n’))

But obviously that doesn’t work. I tried making a list with 0-9 and then saying:

void keyPressed() {
if ((key in list) || (key == ‘\n’))

But that doesn’t work. It feels like there must be a simpler way I’m just missing here…

Then the other issue I was having is:

“If the ‘f’ key is pressed, make a new fish at position (100,100). You can erase any existing fish and forget about them.”

Which ok,
if (key == ‘f’) {
Fish f = new Fish(100,100);

But that doesn’t create a new fish every time the key is pressed, right? It’ll just make it this one time.

Interestingly our next “part” includes instructions to make arrays but this one does not. I’m unsure how to do this without an array, but again, maybe I’m missing something.

1 Like

Hello,

key is an ASCII character; 0 to 9 (key) is 0x30 to 0x39 (hex) or 48 to 57 (decimal)
https://www.processing.org/reference/key.html

You can add key to a string after each keypress.
https://processing.org/reference/addition.html

When you press ‘/n’ (linefeed) stop adding to the String.

Then save it somewhere for later use; keep in mind it is a String and you will have to cast it to an int.

It is only a few lines of code and worth the effort to try this.
It was easy enough to find an example also; I always try first and then look at existing examples.

:slight_smile:

This is NOT complete code but something to get you started:

String entered = "", done = "";

void setup() 
	{
	}

void draw() 
	{
	}

void keyPressed()
  {
  entered += key;
  println (entered);
  if (key == '\n')
    {
    done = entered;
    println("Done!", done);
    }
  }

You still have to check for only valid number keys entered and convert to an int.
https://processing.org/reference/intconvert_.html

1 Like

Hahaha!

Thank you! Of course, I knew I must’ve been missing something silly.

1 Like

You can convert the keys ‘0’ to ‘9’ to their corresponding value like this:

int numKey;

function keyPressed() {
  numKey = key - '0';
  if (keyNum < 0 | keyNum > 9)  keyNum = -1; // Flags as a non-numerical key!
}