Avatar of Kyle Hamilton
Kyle Hamilton
Flag for United States of America asked on

Java - how to generate Random numbers in while loop

I want to generate two random numbers, then check for a condition, and as long as condition holds true, generate two new different random numbers.

This is what I have... and I suspect it's probably wrong...

Random hit = new Random();
				int rowRan = hit.nextInt(9);
				int colRan = hit.nextInt(9);
				
				while(ships[rowRan][colRan] == '-'  || ships[rowRan][colRan] == '*'){
					Random nexthit = new Random();
					rowRan = nexthit.nextInt(9);
					colRan = nexthit.nextInt(9);
				}
				rowInt = rowRan;
				colInt = colRan;

Open in new window

Java

Avatar of undefined
Last Comment
Kyle Hamilton

8/22/2022 - Mon
for_yan

you can do that, i believe, but you actually don't need to craete new Rndom every time:
Random hit = new Random();
				int rowRan = hit.nextInt(9);
				int colRan = hit.nextInt(9);
				
				while(ships[rowRan][colRan] == '-'  || ships[rowRan][colRan] == '*'){
					
					rowRan = hit.nextInt(9);
					colRan = hit.nextInt(9);
				}
				rowInt = rowRan;
				colInt = colRan;
                                  

Open in new window

for_yan

Random hit = new Random();

creates new random value using the cvurren millisecond as a seed,
after that each hit.nextInt(9) will generate a random int less than 9
you do not need to recreate the Random object every time - it will generate different random int less than 9 eech time ytou call it, so you don;t need ti recreate it every time
ASKER CERTIFIED SOLUTION
for_yan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Kyle Hamilton

ASKER
I was hoping for that.

So when is a Random generated with the same "seed" giving you the same random number?

(not sure what I'm talking about... it's something I read..)
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
for_yan

yes,
if you say

Random r = new Random(25345123);

and then you say

int i = r.next(100);
let's assume each time you'll be getting as i say

41, 13, 12, 56...


then somehwre down the roda you again create the Random with the same seed


r = new Random(25345123);

and again do

i = r.nextInt(100);

several tiumes, then you'are guranteed that you'll be getting the same sequence:

41, 13, 12, 56...

That is waht mesans seed. If you use different seemd then sequence will be different

But within each sequence numbers are still coming in random way
So you don't need to create Random object again
Kyle Hamilton

ASKER
cool. That's exactly what I wanted to know....

Thanks.