Good day! I create an array of integer values, the values ​​from 1000 to 9999, inclusive, should be entered into it via for when the program starts. Then I randomly click on a button and select one of the values. I put the size of the array 10,000. As a result, I often get the value 0, although if I output the entire array to the console, then there are no such values. Help me to understand! In the end, at the press of a button, I have to get only one 4-digit number ...

I create an array:

public int passArray[] = new int[10000]; 

I fill in:

 for (int i = 1000; i < passArray.length; i++){ passArray[i] = i; } 

I deduce on clicking of the button:

 int index; index = passArray[(int) (Math.random() * passArray.length)]; System.out.println(Integer.toString(index)); 

As a result, it gives the number, for example, 3443, then once again, it gives 5534, and once again I press and gives 0, I can give 0 again, in general, I can’t understand where they come from ... Tell me!

    2 answers 2

     for (int i = 1000; 

    And what do you think in the array in the elements from 0 to 999? That's just 0.

     int index; index = passArray[; System.out.println(Integer.toString(index)); 
     System.out.println(Integer.toString((int)(Math.random() * 9000) + 1000)); 

      The array is initialized with zeros. In an array of 10,000 items, and you reinitialize only 9000.

      10% chance of getting zero.

      UPDATE:

       public int passArray[] = new int[9000]; for (int i = 0; i < passArray.length; i++){ passArray[i] = i+1000; } 

      Or as in the answer Qwertiy.

      • I also thought about it, but how to reduce the size to fill 9000 starting from 1000 I did not understand .... I already broke my whole head) tell me? - Tim Leyden
      • @TimLeyden, so I answer code without an array. - Qwertiy
      • @Qwertiy, yes, I tried it just ... I had the idea that up to 1000 zeros, but I didn’t know how to “filter” when choosing a number ... and where I didn’t think of slipping this “+1000” )) thank! Now gives as it should;) - Tim Leyden
      • Yes, and this method also works! To this I was closest) Thank you! - Tim Leyden