Dave's Brain

Browse - programming tips - java generate a random integer in a range

Date: 2011nov4
Language: Java

Q.  How can I generate a random integer in a range?

A.  There are two ways.
Use Math.random() if you just want one:

	int number = (int) Math.floor(Math.random() * biggest);		// Gives 0 to biggest - 1


Use the Random class if you want many:

	Random random = new Random();

	int number = random.nextInt(biggest);		// Also gives a number in 0 to biggest - 1

Using the first method, here's a way to make something execute 50% of the time:

	// We generate either 0 or 1 and compare it with 0
	if ((int) Math.floor(Math.random() * 2) == 0) {
		// This will be done half the time
	}
	else {
		// This will also be done half the time
	}

We can put that in a function:

	boolean isCoinTossHeads() {
		return (int) Math.floor(Math.random() * 2) == 0;
	}

	if (isCoinTossHeads()) {
		// its heads
	}
	else {
		// its tails
	}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: