Skip to main content

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

1 reply [Last post]
gmk0232
Offline
Joined: 2012-10-16
Points: 0

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[] Answers = new String[5];
Answers[0]="4";
Answers[1]="5";
Answers[2]="6";
Answers[3]="7";
Answers[4]="8";

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;
if (attempt.equals(Answers[qno]))
{
correct++;
JOptionPane.showMessageDialog(null, "You answered correctly");

}

else
{
incorrect++;
JOptionPane.showMessageDialog(null, "You answered incorrectly");

}

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+"%");

}

}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
shingnpr
Offline
Joined: 2012-09-21
Points: 0

Its better you use collection..Hashtable as it do not allow duplicate and works similar to array.