【问题标题】:Where does my array go out of bounds?我的数组在哪里超出范围?
【发布时间】:2023-04-10 19:08:01
【问题描述】:

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

}

感谢您的帮助!

【问题讨论】:

    标签: java arrays logic indexoutofboundsexception


    【解决方案1】:

    for(int students = startingStudents; startingStudents

    应该是

    for(int students = startingStudents;students

    【讨论】:

    • 顺便说一句……循环结束的lockerPosition应该是++,而不是+=学生。以防万一有人想知道:-)
    【解决方案2】:

    这是你的循环终止

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

    应该是

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

    因此,我猜你得到的不是 ArrayIndexOutOfBoundsException,而是 Heap-Space-Exception。

    【讨论】:

    • 是的,安迪,你是对的。我非常专注于内部逻辑,我们只是略过了 for 循环条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多