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] + " ");
        }
        System.out.println();
        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:
java.lang.IllegalArgumentException:

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

Dani AI

Generated

A quick summary and a safe fix.

The goal is a random permutation of ten integers (each number used once). The initial printout of ten zeros just shows an empty new int[10] (Java fills primitives with zeros). The run-time error comes from using the array value as the bound for Random.nextInt(...) — when that bound is zero you get an IllegalArgumentException. pointed this out, and correctly warned that picking randomly with replacement can produce duplicates.

The simplest, correct approach is to shuffle the source array rather than repeatedly asking for a random element. A Fisher–Yates shuffle produces a uniform permutation in O(n) time and avoids duplicates entirely. Example (shuffle in place and then use the shuffled array):

import java.util.Random;

int[] src = {0,1,2,3,4,5,6,7,8,9};
Random rnd = new Random();

for (int i = src.length - 1; i > 0; i--) {
    int j = rnd.nextInt(i + 1); // 0..i inclusive
    int tmp = src[i];
    src[i] = src[j];
    src[j] = tmp;
}

// src now holds the numbers in random order
for (int v : src) System.out.print(v + " ");

Alternative: convert to a List<Integer> and call Collections.shuffle(list) then copy back to a primitive array if needed. Notes: seed Random only when reproducible output is wanted; for cryptographic uses pick SecureRandom. Also avoid using array element values as bounds — always use lengths or computed ranges that are guaranteed positive. Thanks to for the example code and to and for the diagnostic pointers.

Recommended Answers

All 3 Replies

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:


http://java.sun.com/javase/6/docs/api/index.html?java/util/Random.html

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.

http://www.daniweb.com/code/snippet217217.html
http://www.daniweb.com/code/snippet217346.html

Thanks a lot for all helps . These information is good .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.