# Checking to see if a number is in an array, to stop duplicate random numbers

gmk0232
Offline
Joined: 2012-10-16

Hey folks, I'm trying to avoid having duplicate random numbers in a program. As in part of the patch requires a random number generated each time a loop goes around, but I don't want the same random nuimber to be repeated. Currently I am writing each new random number to an array the doing a binary search(though I don't think I really know how to use it!) to check if subsequent random numbers are in the array.
The program compiles no problem but it still gives out duplicate random numbers.
I have included the file below.
Thanks very much in advance and I look forward to picking everyone's brains over the coming months!

Code:
import javax.swing.JOptionPane;
import java.util.*;

class Quiz {

public static void main (String args[]) {

String[] Questions = new String[5];
Questions[0] = "What is 2 + 2";
Questions[1] = "What is 2 + 3";
Questions[2] = "What is 2 + 4";
Questions[3] = "What is 2 + 5";
Questions[4] = "What is 2 + 6";

int[] rand = new int[5];
rand[0] = 99;
rand[1] = 99;
rand[2] = 99;
rand[3] = 99;
rand[4] = 99;

Arrays.sort(rand);

int correct=0;
int incorrect=0;
int percent=0;
int randcheck=99;
int randomNum=0;
int index;
int y=0;
Random r = new Random();

for (int x=0; x<=4; x++) {

for (index=0; index!=-1;)
{randomNum = r.nextInt(4);
index=Arrays.binarySearch(rand, randomNum);}

rand[y]=randomNum;
y++;

String attempt = JOptionPane.showInputDialog(null, Questions[randomNum]);

int qno=randomNum;
{
correct++;

}

else
{
incorrect++;

}

percent = (correct*100)/5;

}

JOptionPane.showMessageDialog(null, "Thank You For Taking The Quiz \n"+"You got "+correct+" questions right \n"+"You got "+incorrect+" questions wrong \n"+"Your success rate was "+percent+"%");

}

}