Programming Course for Beginners - ZedLX

The Easiest Online Computer Programming Course, for Free

The Type string [9/14]

This program prints out the name of the last key pressed whenever a different key is pressed. It uses the function lastKeyName(). The variable prevKeyName stores the name of the previously pressed key.

Does anything get printed out when the same key is pressed multiple times in a row?

After running and analyzing this program, change it so that it outputs the name of the key even if the same key is pressed multiple times in a row. You need to use the function isPressed(), which returns a value of type bool, to detect when a key is pressed or released. Therefore, even if a user is holding a key down for long time, the program should print out the key name only once. When the same key is released and then pressed down again, the key name should be printed out again.

Solution, part 1:

At the beginning, add: #bool wasPressed=false;

Also, delete the entire if statement together with the println sub-statement.

Solution, part 2:

In the loop, add: #bool isPressedNow = isPressed(keyName);

Solution, part 3:

In the loop, add: if isPressedNow and not wasPressed :println keyName;

Solution, final part:

In the loop, add at end: wasPressed = isPressedNow;

Loading...