Hi to all,
Here there is array of ten position and array contain ten integers .
I want to put the array of ten integers randomly on the array of ten position ...

Here is my code :

import java.util.Random;
public class TestArray {

    public static void main(String[] arg) {
        int[] array;
        int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int size = 10;
        array = new int[size];
        Random random = new Random();
        for (int i = 0; i < array.length; ++i) {
            System.out.print(array[i] + " ");
        for (int i = 0; i < array.length; ++i) {
            array[i] = random.nextInt(arr[i]);
            System.out.println(array[i] + " ");

the first for loop print :
0 0 0 0 0 0 0 0 0 0

In the second for loop i want to put the array of ten integer randomly in the first array
but it give me this exception:

please tell me why this and how can i adjust this ?
thanks in advance

8 Years
Discussion Span
Last Post by beshoyatef

Your first loop is behaving as expected.
There are multiple problems with the second loop.

for (int i = 0; i < array.length; ++i) {
   array[i] = random.nextInt(arr[i]);
   System.out.println(array[i] + " ");

starting with the first line array[i] = random.nextInt(arr[i]); I'm not sure what you're trying to achieve here. if you're trying to get a random value from arr, to put into array, the syntax would be: array[i] = arr[random.nextInt()%arr.length]; The problem with this is that you can have the same value entered at multiple locations, as you have no way of recording which values have already been entered. If this is the expected behavior, then it's fine. If it's not... then I'll leave it up to you to have a go at figuring out how to fix it :P


nextInt (int) requires a positive parameter. You are passing it arr[0], which is 0, which is an error. From the documentation:


public int nextInt(int n) {
   if (n <= 0)
     throw new IllegalArgumentException("n must be positive");

   if ((n & -n) == n)  // i.e., n is a power of 2
     return (int)((n * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % n;
   } while (bits - val + (n-1) < 0);
   return val;

See red above.

If you are trying to shuffle the array, one way to do it is to shuffle the indexes 0 - 9. See this code snippet, written in C++, on how to generate the random numbers 0 - 9 with no repeats. It's written in C++, but you can convert it to Java. In addition, here is a shuffling snippet I wrote in C++, but that can be converted to Java. It's the same concept.


Edited by VernonDozier: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.