Jump to content
Sign in to follow this  
Sigmahokies

trying to prevent repeat random number in array

Recommended Posts

Hi everyone, I am beginner ti learn Java, I am trying to stop the repeat number in array, but it won't work. Anyone who have idea? it will be appericate...here my code to create random number that between 50 to 60, then put in 10 array, but few number are repeated...

	int [] myArray = {0,1,2,3,4,5,6,7,8,9};
	int pop = 0;
	for (int i = 0; i < myArray.length; i++0 {
	pop = (int) ((Math.random() + 5) *10);
	for (int j = 0; j < myArray.length; j++) {
	if (pop != MyArray[j]) {
	myArray[j] = pop;
	}
	 
	

Share this post


Link to post
Share on other sites

You have a typo in that first for loop line.

Your next for loop is going to set every element in myArray to pop.  So you're going to end up with every element in myArray set to whatever the last random number was.  You're looping through myArray and, if the current element is not set to pop, then you set it to pop, so you set every element to pop.

What are you trying to do, are you just trying to get the numbers between 50 and 60 in a random order?

Share this post


Link to post
Share on other sites

Hi justsomeguy,

Yes, i am trying to set up the random between 50 and 60, but not in order. I am trying to create the game. I want to have player 1 and player 2 making a guess number, if it is not match the secret number, then store into array to make sure player 1 and player 2 can't repeat number (like program can check to see if number is exist in array, then guess number that does not exist in array), until player 1 or player 2 make match the secret number to win.

Hey, Please be patient with me if my grammar in english is terrible, because I am fluent in ASL. Thank you so much!

Share this post


Link to post
Share on other sites

If you just want the numbers 50 through 60 in a random order, you can make an array with those numbers and then shuffle it to randomize the order:

http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array

The other option is to keep generating random numbers and checking if they are already in the array before adding them.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×