-5
public void timerCallback()
{
    if (count < 8)
    {
        System.out.println("My timer woke up!");
        this.setOutputState(this.pinNumber, this.pinState);
        this.pinState = !this.pinState;
        this.setTimer(this.timerDelay);
        count++;
    }else
     {
        this.stopMonitoring();
     }
}

That works in the sense that it prints the statement (with the delay) 8 times then terminates the program. Now this:

public void timerCallback()
{
    while (count < 8)
    {
        System.out.println("My timer woke up!");
        this.setOutputState(this.pinNumber, this.pinState);
        this.pinState = !this.pinState;
        this.setTimer(this.timerDelay);
        count++;
    } 
        this.stopMonitoring();
}

That code just prints the statement 8 times at once, then terminates. Why is that?

Struggling
  • 51
  • 2
  • 11
  • Possible duplicate of [Java : Recursion -While Loop Vs If Loop](http://stackoverflow.com/questions/11840294/java-recursion-while-loop-vs-if-loop) – ericbn Jan 04 '16 at 17:53
  • 2
    Your first example requires that `timerCallback()` be called for *each* output of "My timer woke up!", whereas your second example does it all within a loop inside of *one* call to `timerCallback()`. `while` will continue to re-execute the following statement or block until the condition fails. `if` only executes the block once if the condition is true. – lurker Jan 04 '16 at 17:54
  • You'll want to know the difference between `if` and `while`... – ericbn Jan 04 '16 at 17:54
  • Here's a hint... when is `timerCallback()` called? It looks like you want it called 8 times before you `stopMonitoring()`, so what makes it get called 8 times? – Erick G. Hagstrom Jan 04 '16 at 18:22
  • NOT A DUP of the recursion question. This question is all about triggering a callback. There's no recursion here. (Although it does bear some resemblance due to the `while`/`if` confusion...) – Erick G. Hagstrom Jan 04 '16 at 18:24

1 Answers1

0

The purpose of the if/else in the original version is to give the timer eight chances to "wake up" and toggle pin state before invoking stopMonitoring(). Printing the message is secondary. So the if/else checks to see if timerCallback() has been called 8 times. If it hasn't, ok, print the message and give it another chance.

By substituting a while, you just end up printing the message 8 times, toggling pin state back and forth rapidly without checking to see if it helps, and then dropping into stopMonitoring(). So you stop monitoring after the first call to timerCallback(), not the eighth.

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38