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 › loop case in switch
Page Index Toggle Pages: 1
loop case in switch (Read 1226 times)
loop case in switch
May 25th, 2010, 2:25pm
 
hello,
i want num keys to trigger events.
is it possible to loop case somehow?

here's the idea:

Quote:
switch (key)
{
 for (int i=1;i<10;i++){
 case  i:
   println("you pressed "+i);
   break;
 }
}



Re: loop case in switch
Reply #1 - May 25th, 2010, 2:58pm
 
no, the 'arguments' to case statements must be known at compile time.

but there's no need for the case or loop:

  println("you pressed "+ key);

probably should put a check in there to make sure that it's a digit.

if you want the number associated with the key (key is a single character, not a number) then take '0' away from it.

int ch = key - '0';
Re: loop case in switch
Reply #2 - May 25th, 2010, 4:06pm
 
here's my original code, and i was looking for solution to avoid copypasting:

Code:

switch (key) {

 case '1':
   piano[0].x=mouseX;
   piano[0].w=piano[0].x*2;
   break;
 case '2':
   piano[1].x=mouseX;
   piano[1].w=(piano[1].x-(piano[0].x+piano[0].w/2))*2;
   break;
 case '3':
   piano[2].x=mouseX;
   piano[2].w=(piano[2].x-(piano[1].x+piano[1].w/2))*2;
   break;
 case '4':
   piano[3].x=mouseX;
   piano[3].w=(piano[3].x-(piano[2].x+piano[2].w/2))*2;
   break;
 case '5':
   piano[4].x=mouseX;
   piano[4].w=(piano[4].x-(piano[3].x+piano[3].w/2))*2;
   break;
 case '6':
   piano[5].x=mouseX;
   piano[5].w=(piano[5].x-(piano[4].x+piano[4].w/2))*2;
   break;
 case '7':
   piano[6].x=mouseX;
   piano[6].w=(piano[6].x-(piano[5].x+piano[5].w/2))*2;
   break;
 case '8':
   piano[7].x=mouseX;
   piano[7].w=(piano[7].x-(piano[6].x+piano[6].w/2))*2;
   break;
}


anyway thanks:)
Re: loop case in switch
Reply #3 - May 25th, 2010, 10:20pm
 
Code:
int idx = key - '1';
piano[idx].x = mouseX;
int prev = 0;
if (idx > 0)
{
 prev = piano[idx-1].x + piano[idx-1].w/2;
}
piano[idx].w = (piano[idx].x - prev) * 2;

(untested)
Page Index Toggle Pages: 1