random number in range java

random number in range java

Code

refer to‮l:‬autturi.com
// generate a random number from lowerbound(inclusive) to upperbound (inclusive)
Random rand = new Random();
int random_integer = rand.nextInt(upperbound-lowerbound+1) + lowerbound;

// generate a random number from lowerbound(inclusive) to upperbound (exclusive)
Random rand = new Random();
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;

Example - get random numbers in a specific range in java

/**
 * @author lautturi.com 
 * Java example: generate a random int value from 1 to 100 in java
 */

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {
		
		Random random = new Random();

		int min = 1;
		int max = 100;

		int randomNum = random.nextInt(max + 1 - min) + min;
		
		System.out.println("random number:"+randomNum);
	}

}
Created Time:2017-10-06 13:46:55  Author:lautturi