-4

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;
}
XO56
  • 332
  • 1
  • 12
Fisch101
  • 3
  • 3
  • What is `n`? What is `peopleindex`? You are also missing an ending `}` – Spectric Feb 21 '21 at 05:15
  • `int birthday = (int) (Math.random() * n);` Sometimes this line will give you `indexoutofbound` error. – XO56 Feb 21 '21 at 05:27
  • @XO56 `random` never returns a value of `1.0`. But could it return a value very close to 1 so that it actually is 1? – Gautham M Feb 21 '21 at 05:45
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Feb 21 '21 at 05:56
  • On every iteration, you create a new boolean array, with all values defaulting to false, so the `if` statement is always true, since `birthdaypeople[birthday]` is always false, which means the `else` block never executes, and therefore never reaches the `break` statement. – Andreas Feb 21 '21 at 05:57
  • @GauthamM until you use `ceil()` method it never become `1`. Besides, close to `1` doesn't mean exactly `1`. – XO56 Feb 21 '21 at 12:46
  • 1
    @XO56 Then how could `(int) (Math.random() * n)` cause an index out of bound error as it could never be `>=n`. Also, if we do initialize a double with `0.99999999999999999999999999d` it actually becomes 1. But I am not sure if `random` would return a value this close to 1. – Gautham M Feb 21 '21 at 13:35
  • @GauthamM yup! you're right!.... Thank you :) – XO56 Feb 21 '21 at 13:37

1 Answers1

0

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;
     }
 }
Gautham M
  • 4,816
  • 3
  • 15
  • 37
Beshambher Chaukhwan
  • 1,418
  • 2
  • 9
  • 13