Issue
I am trying to generate an array filled with random numbers, no duplicates and all of them have to be even and greater than 1. Sadly in my code i often get a "0" in my array but i dont really know how to fix it. Here is the code:
{
public int[] rArray; // our array
RandomArray(int arrayLength, int MaxValue)
{
rArray = new int[arrayLength];
Random randNum = new Random();
for(int p=0; p<arrayLength;p++)
for (int i = 0; i <= rArray.length; i++)
{
boolean exist = true;
while (exist)
{
exist = false;//
int x = randNum.nextInt(2,MaxValue);
for (int k = 0; k < i; k++)
{
if (x == rArray[k] )
{
exist = true;
break;
}
}
if (!exist && x % 2 == 0)
{
rArray[p] = x;
}
}
}
}
Solution
When using an int[]
of a certain size the values of the array are 0, as that is the default value of an int
(a primitive).
In your loop you are checking if the value doesn't exist and is even, if not you skip over an element in the array leaving the 0.
for (int i = 0; i <= rArray.length; i++) {
boolean exist = true;
while (exist) {
exist = false;//
int x = randNum.nextInt(2,MaxValue);
for (int k = 0; k < i; k++) {
if (x == rArray[k] ) {
exist = true;
break;
}
}
if (!exist && x % 2 == 0) {
rArray[p] = x;
}
}
}
If the random number is 3, that will not exist, and isn't even either. It will leave the while
loop, not having set rArray[p]
and the outer loop will advance to the next one, leaving the 0.
What you should do is first check if the value is even, if not generate a new numnber.
for (int i = 0; i < rArray.length; i++) {
boolean exist = true;
while (exist) {
exist = false;//
int x = 1;
while (((x = randNum.nextInt(2, MaxValue)) % 2) != 0) {}
}
for (int k = 0; k < i; k++) {
if (x == rArray[k] ) {
exist = true;
break;
}
}
if (!exist) {
rArray[i] = x;
}
}
}
Now using streams this would be a lot easier to achieve
rArray= ThreadLocalRandom.current().ints(2, MaxValue)
.filter(it -> (it % 2) == 0)
.distinct().limit(arrayLength).toArray();
Would yield the same result.
Answered By - M. Deinum
Answer Checked By - Clifford M. (JavaFixing Volunteer)