質問

私はこれのためのアルゴリズムを書いています:100人の学生と100個のロッカーがあります。最初の生徒は最初のロッカーから始まり、一人一人を開きます。次の学生、学生2は、2番目のロッカーから始まり、それが開いている場合は毎秒毎回のロッカーを閉じます。3人目の学生は3番目のロッカーから始まり、3番目のロッカーごとにプロセスを繰り返します。私は働くべきだと私が信じる何かを書いたが、私の配列は範囲外に出ていて、私はどのように見えない:

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 Semendent=始動率; 始動集 <= 100;学生++)

であるべきです

(int学生=始動; 学生 <= 100;学生++)

他のヒント

あなたのループ終端

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

であるべきです

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

したがって、私はあなたがArrayIndexOutOfBoundSexceptionを取得していないと思いますが、heap-space-exception。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top