Domanda

Sto cercando di scrivere un algoritmo per questo: ci sono 100 studenti e 100 armadietti.Il primo studente inizia al primo armadietto e apre tutti.Il prossimo studente, gli studenti due, inizia al secondo armadietto e chiude ogni secondo armadietto se è aperto, e viceversa.I terzi gli studenti iniziano al terzo armadietto e per ogni terzo armadietto, ripete il processo.Ho scritto qualcosa che credo dovrebbe funzionare, ma il mio array sta andando fuori dai limiti e non vedo come:

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);
    }

}
.

Grazie per qualsiasi aiuto!

È stato utile?

Soluzione

per (Int Students= Interventudents; Avvio degli inizi <= 100; Studenti ++)

dovrebbe essere

per (int Students= Studenti di partenza; Studenti <= 100; Studenti ++)

Altri suggerimenti

È la tua terminazione ad anello

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

dovrebbe essere

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

Pertanto, immagino che tu non stia ottenendo un'arrayindexoutofboundsexception, ma un mucchio-spazio-eccezione.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top