This site requires JavaScript, please enable it in your browser!
Greenfoot back
BrownBoii333
BrownBoii333 wrote ...

2014/11/25

How to make an int go up once

BrownBoii333 BrownBoii333

2014/11/25

#
I have: x++ in an if statement, and it's is constantly going up when that if statement is acting. how do i make it go up once when i hit a button (the if statement is Greenfoot.isKeyDown);
davmac davmac

2014/11/25

#
By button do you mean key, and, if the button is hit twice, do you want to increment the variable twice, or only once?
danpost danpost

2014/11/25

#
You need to track the state of the button and incorporate it into your 'if' condition and add another 'if' -- one 'if' for button press and the other for button release.
davmac davmac

2014/11/25

#
You need to track the state of the button and incorporate it into your 'if' condition and add another 'if' -- one 'if' for button press and the other for button release.
I believe this makes the assumption that the answer to my second question would be "yes, increment the variable twice if the key is pressed twice".
danpost danpost

2014/11/25

#
@davmac, in this case, I am convinced that there was sufficient evidence given to conclude that nothing was misleading. What was given suggests something like this:
1
if (Greenfoot.isKeyDown("up")) x++;
the if statement is Greenfoot.isKeyDown;
was attemped, but for the time the button was down, the value kept increasing:
constantly going up when that if statement is acting
but, wanting it to only increment once
how do i make it go up once when i hit a button
davmac davmac

2014/11/25

#
I think you are probably right, but I wanted to clarify, because the question says:
How to make an int go up once
With your suggested solution, the value might be incremented more than once (it will be incremented each time the key is pressed). That is why I asked my question - I wanted to determine whether the asker really meant "once" or "once per keypress".
BrownBoii333 BrownBoii333

2014/11/25

#
Danpost is correct. So how would I do that. Sorry I'm kind of knew at coding
danpost danpost

2014/11/25

#
Add an instance boolean field to the class for tracking the state of the button -- call it 'buttonDown' (or you can be more specific and give the button name in the field name; like 'spaceDown' or 'xDown'). The two conditions for incrementing on a button down action would be (1) the 'buttonDown' field is currently 'false' and (2) the 'isKeyDown' method returns 'true'. The two conditions for the button up action would be (1) the 'buttonDown' field is currently 'true' and (2) the 'isKeyDown' method returns 'false'. In both 'if' blocks, you will change the value of the 'buttonDown' field and in the first 'if' block, you will also increment the value of 'x'.
You need to login to post a reply.