We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Text input - Numbers only
Page Index Toggle Pages: 1
Text input - Numbers only (Read 994 times)
Text input - Numbers only
Dec 23rd, 2009, 5:23am
 
I'm want to prompt the user for text input, but only accept numbers and ignore everything else.

Other than using 10 if statements, is there a quicker way of doing this?

Thanks,

TB
Re: Text input - Numbers only
Reply #1 - Dec 23rd, 2009, 5:26am
 
Integers or decimals?
Re: Text input - Numbers only
Reply #2 - Dec 23rd, 2009, 5:27am
 
integers -

to be more precise if it helps:

i want each key press to be added to an array
Re: Text input - Numbers only
Reply #3 - Dec 23rd, 2009, 6:21am
 
The following code will differentiate between digit (0-9) and all other key presses.

Code:
int n;

void draw() { } // Empty draw() needed to keep the program running

void keyPressed() {
// get the value of the key pressed
n = int(key); // int('0') = 48
n = n - 48;
if(n >= 0 && n <= 9){
println("Valid digit: " + n);
}
else {
println("Invalid you pressed " + key);
}
}


Hope it helps.
Re: Text input - Numbers only
Reply #4 - Dec 23rd, 2009, 6:26am
 
Terry_Bell wrote on Dec 23rd, 2009, 5:27am:
integers -

to be more precise if it helps:

i want each key press to be added to an array

More precise is required, not just helpful!  Smiley

Consider:

Code:
switch (key)
{
 case '0':
 case '1':
 case '2':
 case '3':
 case '4':
 case '5':
 case '6':
 case '7':
 case '8':
 case '9':
   // do something
   break;
 default:
   // do something else
}


or

Code:
if ('0' <= key && key <= '9')
{
 // do something
}
else
{
 // do something else
}


In the "do something" part, you might like to do something starting like so:

Code:
int digit = key - '0'; 



Since it is still unclear what you mean for a sequence of digits entered (are they to be combined into a single integer, or a simple sequence of one-digit values?), I leave it up to you to figure out what to do next.

-spxl
Page Index Toggle Pages: 1