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

时间:2016-01-04 17:50:33

标签: java if-statement interface while-loop hardware-interface

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次,然后终止。这是为什么?

1 个答案:

答案 0 :(得分:0)

原始版本中if/else的目的是让计时器有八次机会醒来&#34;并在调用stopMonitoring()之前切换引脚状态。打印邮件是次要的。因此,if/else会检查timerCallback()是否已被调用8次。如果它还没有,那么打印信息再给它一次机会。

通过替换while,您最终会打印消息8次,快速切换针状态而不检查是否有帮助,然后进入stopMonitoring()。所以你在第一次打电话timerCallback()后停止监听,而不是第八次。

相关问题