1

I want to print out an array of those 100 numbers. However, my program stops after generating certain amount of numbers. Here's my code.

class A4
    public static void main(String[] args)
    {
        int[] array1 = new int[101];
        int num, i = 0;
        boolean repeat = false;
        while(i < 100)
        {   
            num = (int) (Math.random() * 100) + 1;
            array1[(i)] = num;
            for (int e = 0; e < i; e++)
            {
                if (num == array1[e])
                    repeat = true;
            }

            if (repeat == true)
            {
                continue;
            }

            array1[i] = num;
            System.out.println(array1[i]);
            i++;
        }
    }
}
nbrooks
  • 17,489
  • 5
  • 46
  • 61
  • The linked question does not account for the numbers being unique, and is not a duplicate in this case. – nbrooks Dec 12 '18 at 03:20
  • @nbrooks updated. It's most definitely a duplicate. – Andy Turner Dec 12 '18 at 03:21
  • 1
    If you want to generate 100 distinct random numbers in the range 1-100, you should just populate the array with the numbers 1-100 and shuffle it. – Andy Turner Dec 12 '18 at 03:22
  • @AndyTurner Well, that's the solution I intended to propose. Agreed that the updated link is a true dupe though. – nbrooks Dec 12 '18 at 03:24
  • 1
    The actual problem in this code is that you don't reset `repeat` to false once you have found a repeat. One of the takeaways here is to always declare variables in the tightest possible scope - i.e. inside the while loop - to avoid accidentally reusing values you didn't intend to. – Andy Turner Dec 12 '18 at 03:29
  • Thank every one. Problem solved. I just need to declare repeat variable in while loop like Andy Turner said. – Cuoc Doi Cam On Dec 12 '18 at 04:47

0 Answers0