while while循环 - 仅循环两次 - 应该循环8次

时间:2014-02-28 17:33:08

标签: java

这个循环只循环两次......

    int currentPosition = 10;
    int nextPosition;
    do
    {
        nextPosition = currentPosition + 1;
        sectionSem[nextPosition].P(); // wait for the section ahead to be
                                        // free
        trackSections[nextPosition] = "[A" + trainName + "]"; // move
                                                                // forward
        trackSections[currentPosition] = "[..]"; // clear section vacated
        // record the train activity
        theTrainActivity.addMovedTo(nextPosition);
        sectionSem[currentPosition].V(); // signal the section you vacated
                                            // now free
        currentPosition += 1;
    } while (currentPosition < 18);

知道为什么吗?它应该循环8次?!

1 个答案:

答案 0 :(得分:0)

代码中的错误位于此处:

    sectionSem[nextPosition].P(); // wait for the section ahead to be
                                    // free
    trackSections[nextPosition] = "[A" + trainName + "]"; // move
                                                            // forward
    trackSections[currentPosition] = "[..]"; // clear section vacated
    // record the train activity
    theTrainActivity.addMovedTo(nextPosition);
    sectionSem[currentPosition].V(); // signal the section you vacated
                                        // now free

如果你把循环简化为这样:

public static void main(String []args){
        int currentPosition = 10;
        int nextPosition;
        do
        {
            nextPosition = currentPosition + 1;         
            System.out.println("nextPosition = " + currentPosition);
            currentPosition += 1;
            System.out.println("currentPosition = " + currentPosition);
        } while (currentPosition < 18);
     }

它运行8次。输出如下:

nextPosition = 10
currentPosition = 11
nextPosition = 11
currentPosition = 12
nextPosition = 12
currentPosition = 13
nextPosition = 13
currentPosition = 14
nextPosition = 14
currentPosition = 15
nextPosition = 15
currentPosition = 16
nextPosition = 16
currentPosition = 17
nextPosition = 17
currentPosition = 18