为什么这段代码适用于 if 语句而不是 while 循环


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();
     }
}

从某种意义上说,它打印语句(带延迟(8次,然后终止程序。现在这个:

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();
}

该代码一次打印语句 8 次,然后终止。为什么?

原始版本中if/else的目的是在调用stopMonitoring()之前给计时器八次"唤醒"和切换引脚状态的机会。打印消息是次要的。因此,if/else会检查timerCallback()是否被调用了 8 次。如果没有,好的,打印消息并再给它一次机会。

通过替换while,您最终只需打印消息 8 次,快速来回切换引脚状态而不检查是否有帮助,然后进入stopMonitoring()。因此,您在第一次调用timerCallback()后停止监视,而不是第八次。

最新更新