JavaBeat Certifications Certifications Kits Articles Interview Questions OCAJP 7 OCPJP 5 OCPJP 6 OCEJWCD 6 SCBCD 5.0 SCEA SCJA

How can I generate random numbers?

Topic :
Feedback Request New QnA Print Email

Generating random numbers is simple. Provided as part of the java.util package, the Random class makes it easy to generate numbers. Start by creating an instance of the Random class

// Create an instance of the random class
Random r = new Random();

Now, you must request a number from the generator. Supposing we wanted an integer number, we'd call the nextInt() method.

// Get an integer
int number = r.nextInt();

Often you'll want numbers to fall in a specific range (for example, from one to ten). We can use the modulus operator to limit the range of the numbers. This will give us the remainder of the number when divided by ten (giving us a range -9 to +9). To eliminate negative numbers, if the number is less than one we'll add ten to it. This gives us random numbers between one and ten!

// Accept only up to ten
int random_number = number % 10;
if (random_number < 1) random_number = random_number + 10;

Creating random numbers in an application or applet really isn't that difficult. Just remember to limit the range of your numbers, and to import the java.util.Random class.

Topic :
Feedback Request New QnA Print Email

All api java java 6.0 java 7.0 jdbc jsp servlet ejb jndi jms ejb 3.0 j2ee jee 5.0 jee 6.0 jsf struts spring Hibernate ajax JBoss Seam netbeans eclipse ant xml maven dojo junit javafx j2me log4j ESB JBoss Apache Quartz scjp mysql oracle gwt openjpa jmx yui google-guice android JBoss scwcd 5.0 scjp 1.5 scjp 1.6 scja scbcd 5.0

javabeat | advertise | about us | contact | useful resources
Copyright (2004 - 2013), JavaBeat