2012-09-29 121 views
0

我想爲此寫一個算法:有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); 
    } 

} 

感謝您的幫助!

回答

2

的for(int學生= startingStudents; startingStudents < = 100;學生++)

應該是

的for(int學生= startingStudents; 學生 < = 100;學生++)

+0

Wooooow ....這就是我得到的編碼睡眠剝奪。謝謝肖恩。 –

+0

順便說一句...循環結束時的lockerPosition應該是++,而不是+ =學生。以防萬一有人想知道:-) –

0

這是你的環路終端

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

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

因此,我想你沒有得到一個ArrayIndexOutOfBoundsException,但堆 - 空間 - 例外。

+0

是的,你是對的。我非常關注內部邏輯我的眼睛,我們只是略過了for循環條件。 –