Suppose we are in an environment where CLICK, TICK, and KEY events can occur, and we have the following functions available:
onClick(closure)
Executesclosureafter every subsequentCLICKevent.
onKeyPress(closure)
Executesclosureafter every subsequentKEYevent.
afterDelay(tickCount, closure)
Executesclosureonce after exactlytickCountTICKevents have occurred.
twice(closure)
Immediately executes closure two times.
Multiple closures can be registered to handle the same event. If this happens, they execute in the order they were registered.
Consider the following code:
A onClick(() -> B); C onClick(() -> { D afterDelay(2, () -> { E onClick(() -> F); G }); H twice(() -> I); J }); K afterDelay(3, () -> { L afterDelay(1, () -> { M onKeyPress(() -> N); O }); P twice(() -> { Q onClick(() -> R); S }); T }); U onClick(() -> V); W
Write out the order in which all the marked statements will execute given the following sequence of events (showing both the marked statements and the event names):
TICK CLICK TICK CLICK KEY TICK TICK CLICK CLICK TICK TICK
A TICK CLICK B D I I V TICK CLICK B D I I V KEY TICK TICK L Q Q E CLICK B D I I V R R F CLICK B D I I V R R F TICK E TICK M AFTER C K U W H J H J P S S T G H J H J G O
Consider the following code:
public class StatefulPuzzle {
private int x = 0;
public void run() {
onClick(() -> {
x++;
System.out.println("x=" + x);
});
if (x > 0) {
onClick(() -> {
System.out.println("Hi!");
});
}
onClick(() -> {
if (x > 1) {
System.out.println("Bye!");
}
});
System.out.println("End of run()");
}
}
Given a call to run() followed by two CLICK events, what would this code print?
End of run() x=1 Hi! x=2 Hi!
Related puzzles: