Reputation:
I am beginner in android.
display random numbers of images, kids have to count number images
for answer generate 4 random choice, code is working fine
but sometimes app get hanged, can't optimize code.
Generate Answer
int[] answer = new int[4];
int count=0,random_integer;
while(count<=3){
random_integer = r.nextInt((imageCount+2) - (imageCount-2)) + (imageCount-2);
if(!exists(random_integer,answer)){
answer[count] = random_integer;
Log.d("answer","Array " + count + " = " + random_integer);
count++;
}
}
if(!exists(imageCount,answer)){
answer[r.nextInt(3 - 0) + 0] = imageCount;
}
Check Duplicate
public boolean exists(int number, int[] array) {
if (number == -1)
return true;
for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}
Logcat
While generating 4 value it stopped
Thanks in advance
Upvotes: 0
Views: 54
Reputation: 43738
The answer array is initialized with zeroes. This means, a random_integer
of 0 will not be accepted by the exists
check.
In the case that imageCount
is 2, the only four possible random answers are 0, 1, 2, 3. Since 0 is not accepted, the while loop will never terminate.
A similar problem appears if imageCount
is smaller than 2.
Upvotes: 1