java - 我的数组哪里出界了?

标签 java arrays logic indexoutofboundsexception

我正在尝试为此编写一个算法:有 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 Students =startingStudents; startingStudents <= 100; Students++)

应该是

for(int Students =startingStudents; 学生<= 100; Students++)

关于java - 我的数组哪里出界了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649863/

相关文章:

java - 学习 C/C++ 和 Java

iOS swift : How to store the index of all duplicate values in array?

php - 找到从 A 点到 B 的路径,循环次数为 n

java - 如何让两个 JPanel 水平拆分,每个 JPanel 始终占据屏幕的一半?

java - 从嵌套的用户定义对象中创建 DataFrame

java - 在Intellij中,当我提取一个ArrayList变量时,如何在左侧获得一个List?

java - 带有 switch 语句的基本数组

c - 合并两个与第三个数组大小相同的数组元素而不消除重复元素

c++ - 如何简化检查一对数字是(1,2)还是(2,1)?

logic - 斑马谜题的真值表