我想爲此寫一個算法:有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);
}
}
感謝您的幫助!
Wooooow ....這就是我得到的編碼睡眠剝奪。謝謝肖恩。 –
順便說一句...循環結束時的lockerPosition應該是++,而不是+ =學生。以防萬一有人想知道:-) –