내 배열은 어디에 범위를 벗어 났습니까?
-
11-12-2019 - |
문제
나는이를위한 알고리즘을 작성하려고 노력하고 있습니다 : 100 명의 학생과 100 개의 사물함이 있습니다.첫 번째 학생은 첫 번째 로커에서 시작하여 모든 것을 열어줍니다.다음 학생 인 학생 2는 두 번째 로커에서 시작하여 열려있는 경우 모든 두 번째 로커를 닫고 그 반대의 경우도 마찬가지입니다.세 번째 학생들은 세 번째 사물함에서 시작하고 세 번째 로커마다 프로세스를 반복합니다.나는 일해야한다고 믿는 것을 썼다. 그러나 배열은 경계에서 벗어나고 어떻게 보이지 않는다 :
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);
}
}
.
도움말셔서!
해결책
(int students= stortingstuds; stortingsudents <= 100; 학생 ++)
는 이어야합니다
(int students= stortystudents; 학생 <= 100)
다른 팁
루프 종료
for(int students = startingStudents; startingStudents <= 100; students++)
.
는 이어야합니다
for(int students = 1; students <= 100; students++)
.
은 ArrayIndexOutOfBoundsException을 가져 오지 않고 힙 공간 예외를 가져 오지 않습니다.
제휴하지 않습니다 StackOverflow