All In One Script



PHP,HTLM,CSS,Jquery,AJAX,Javascript and etc doubts and sample codes

  • Home
  • Javascript
  • PHP
  • CSS
  • SQL/MYSQL

How to generate random integers within a specific range in Java?

by Blogger 5:40:00 AM integer java random

How to generate random integers within a specific range in Java?

I am trying to generate a random intvalue with Java, but in a specific range.
For example:
My range is 5-10, meaning that 5 is the smallest possible value and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.
In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. In the class Random there is the method nextInt(int n), which returns a random intvalue in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random integer value between two numbers.
I have tried the following things, but I still have problems: (minimum and maximum are the smallest and biggest numbers).
Solution 1:
randomNum = minimum + (int)(Math.random() * maximum); 
Problem:
randomNum can be bigger than maximum.
Solution 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
Problem:
randomNum can be smaller than minimum.
How do I solve these problems?
I have tried also browsing through the archive and found:
  • Expand a random range from 1–5 to 1–7
  • Generate random numbers uniformly over an entire range
But I couldn't solve the problem.


Solution:

In Java 1.7 or later, the standard way to do this is as follows:
import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.
Before Java 1.7, the standard way to do this is as follows:
import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

http://stackoverflow.com/questions/363681/how-to-generate-random-integers-within-a-specific-range-in-java


READ MORE
SHARE :

Search This Blog

Followers

  • Popular
  • Recent
  • Comments
    How to get Real IP,ISP,Country,City and etc from Visitor using PHP
    Get first key in a (possibly) associative array?
    Solved : curl_init() function not working in Ubuntu
    Does finally always execute in Java?
    How can I make the cursor a hand when a user hovers over a list item?
    How to efficiently iterate over each Entry in a Map?
    Window clearTimeout() Method
    Serving XHTML and self-closing tags
    Length of a JavaScript object
    How to check if PHP array is associative or sequential?

Instagram

About

Popular Posts

  • How to get Real IP,ISP,Country,City and etc from Visitor using PHP
    How to get Real IP,ISP,Country,City and etc from Visitor using PHP Php Get Real visiter's IP and ISP and Country and City and Countr...
  • Get first key in a (possibly) associative array?
    Get first key in a (possibly) associative array? What's the best way to determine the first key in a possibly associative array? My...
  • Solved : curl_init() function not working in Ubuntu
    Solved : curl_init() function not working in Ubuntu  Here solved the error  Fatal error: Call to undefined function curl_init() ...
  • Does finally always execute in Java?
    Does finally always execute in Java? I have a try/catch block with  return s inside it. Will the finally block be called? For example...
  • How can I make the cursor a hand when a user hovers over a list item?
    How can I make the cursor a hand when a user hovers over a list item? I've got a list, and I have a click handler for its items: ...
  • How to efficiently iterate over each Entry in a Map?
    How to efficiently iterate over each Entry in a Map? If I have an object implementing the  Map  interface in Java and I wish to iterate...
  • Window clearTimeout() Method
    Window clearTimeout() Method Definition and Usage The clearTimeout() method clears a timer set with the setTimeout() method. ...
  • Serving XHTML and self-closing tags
    Serving XHTML and self-closing tags I am trying to follow the xhtml 1.0 strict standard as I am creating my website. Right now, validat...
  • Length of a JavaScript object
    Length of a JavaScript object If I have a JavaScript object, say var myObject = new Object (); myObject [ "firstname" ] ...
  • How to check if PHP array is associative or sequential?
    How to check if PHP array is associative or sequential? PHP treats all arrays as associative, so there aren't any built in function...

statcounter



statcounter



Template Created By ThemeXpose & Blogger Templates