我正在试着写一个算法:有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);
}
}谢谢你的帮助!
发布于 2012-09-29 12:20:19
用于(int学生= startingStudents;startingStudents <= 100;students++)
应该是
用于(int students = startingStudents;students<= 100;students++)
发布于 2012-09-29 12:29:57
这是你的循环终结点
for(int students = startingStudents; startingStudents <= 100; students++)应该是
for(int students = 1; students <= 100; students++)因此,我猜你得到的不是一个ArrayIndexOutOfBoundsException,而是一个堆空间异常。
https://stackoverflow.com/questions/12649863
复制相似问题