i have a for loop and inside i have some code. i want to run this code random. i was thinking of using a if statment.

for(int i = 0; i < 50; i++)
{
    if(ran.nextInt(50) > 50/2){
        //code
     }
}

but i want it so its even more random. any idea?

Recommended Answers

All 5 Replies

not sure if "more" or "less" random really make much sense mathematically ...

but maybe you could try a switch - case block , and run different code for different cases for different output of the random method.. that way , you can easily write up an increasing number of cases and well.. make it feel more random...

what do you mean: "I want to run this code random"?
google Java 'roll dice', that 'll give you tons of examples where there's a random number generator for the numbers 1 - 6

"more random"? I don't know what that means.
If your code is intended to enter the if block half the time at random, just use
if (ran.nextBoolean())
... which is as random as Sun's mathematicians know how to make it.

If your code is intended to enter the if block half the time at random, just use

actually, there's no guarantee it will be executed half the time, or anywhere near half the time. That's what random means :)
Over an indefinitely long number of executions most likely it will be roughly half the time, but over any finite number there's no such statement as can be made except that the more iterations, the more likely it is to approach 50%.

Let me re-phrase that "half the time at random" .... how about "with a 50% probability at each iteration"?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.