Skip to content
Advertisement

Why the “break” in the loop doesn’t fuction [closed]

i am doing the coursera homework, but even i use a break in this loop, it seems not break, and i searched how to break a for loop, but i still can’t understand what i do is wrong. Could some nice guys explain it to me?

for (int j = 0; j < n; j++) {
    boolean[] birthdaypeople = new boolean[n];
    int birthday = (int) (Math.random() * n);
    if (!birthdaypeople[birthday]) {
        birthdaypeople[birthday] = true;
    }
    else {
        peopleindex[j + 1]++;
        break;
}

Advertisement

Answer

You are initialising your birthdaypeople array everytime in each iteration which is why the else block is never executed because for every j the birthdaypeople array is new and have false value. Take out the array declaration out of the for loop.

 boolean[] birthdaypeople = new boolean[n];
  
 for (int j = 0; j < n; j++) {
     int birthday = (int) (Math.random() % n);
     if (!birthdaypeople[birthday]) {
         birthdaypeople[birthday] = true;
     } else {
         peopleindex[j + 1]++;
         break;
     }
 }
Advertisement