I've the below code in java. Here i'm trying to see the random combinations of an array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Dummy {
public static void main(String args[]) throws Exception {
Random rand = new Random();
int[] a = { 1, 2, 3, 4, 5 };
int[] b = { 1, 0, 1, 0, 1 };
Arrays.sort(a);
Arrays.sort(b);
int x = a.length * b.length;
System.out.println(x);
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 25; i++) {
System.out.println("random of i is" + a[rand.nextInt(i)]
+ "and j is " + b[rand.nextInt(i)]);
}
System.out.println(list);
}
}
and here i'm getting the below error.
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Unknown Source)
at Dummy.main(Dummy.java:20)
please let me know how to fix it. Based on some other posts based on similar issue, i found that only positive numbers are to be given in Random, i want to know how i can give negative numbers also.
Also i want to know how many combinations i can get by perpetuating a[] and b[].
Thanks
Your error is because of you are passing 0 in rand.nextInt(i).
rand.nextInt() expects positive integer greater that 0.
You are looping the array with maximum of 25 and with 0,
Change the maximum upto the size of the array and then initialize the i greater than zero
otherwise you'll get ArrayIndexOutOfBoundsException
Do like this
for (int i = 1; i <= a.length; i++) {
System.out.println("random of i is" + a[rand.nextInt(i)]
+ "and j is " + b[rand.nextInt(i)]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With