我试图为此编写算法:有100名学生和100个储物柜。第一个学生从第一封储物柜开始,打开每一个。下一个学生学生两人开始在第二个储物柜上开始,如果它打开,则关闭每个第二个储物柜,反之亦然。第三学生从第三个储物柜开始,并且每隔三个储物柜重复该过程。我写了一些我相信应该工作的东西,但我的阵列正在灭亡,我没有看到如何:

public static void main(String[] args) 
{
    int startingStudents = 1;
    int lockersToCheck = 1;
    int lockersPosition = 1;
    boolean[] lockers = new boolean[101];

    //Cycles through 100 students
    for(int students = startingStudents; startingStudents <= 100; students++)
    {
        //What each student does
        while(lockersToCheck <= 100)
        {
                            //If its closed, open
            if(lockers[lockersToCheck] == false)
            {
                lockers[lockersToCheck] = true;
            }
                            //If its open, close
            else
            {
                lockers[lockersToCheck] = false;
            }

                            //Which locker they should be at
            lockersToCheck += lockersPosition;
        }


        //Zero out to start at the right locker
        lockersToCheck = 0;
                    //Where the next student starts
        lockersPosition += students;
                    //Make sure the next student starts there
        lockersToCheck = lockersPosition;

    }

    for(int n = 1; n <= 100; n++)
    {
        System.out.print(lockers[n] + " " + n);
    }

}
.

谢谢任何帮助!

有帮助吗?

解决方案

for(int学生=实践证件; 起始人 <= 100;学生++)

应该是

for(int学生=实践证件; 学生 <= 100;学生++)

其他提示

是你的循环终止

for(int students = startingStudents; startingStudents <= 100; students++)
.

应该是

for(int students = 1; students <= 100; students++)
.

因此,我猜你没有得到一个arrayIndexoutofboundsexception,而是一个堆空间例外。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top