Getting Random Numbers in Java

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;


int random = (int)(Math.random() * 50 + 1);

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

Getting random numbers in Java between two numbers

The static method Math.random() returns a number between 0 and 1 so you just have to multiply the result with the difference between you minimal and maximal value and add this to your minimal value.

int min = 65;
int max = 122;
int random = (int) min + (max - min) * Math.random();

Generating random number in Java

use 100 as argument in nextInt()


Update based on your comment

just create a new static method

public static int genRandom(){
return new Random().nextInt(100);// or may be cache random instance

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

Generate three Random numbers with sum add to predefined value in java, where 3 numbers stored in 3 different textfields?

You could use Math.random() instead of the Random class. Math.random() returns a double between 0 and 1. So the only thing you have to do is multiply the result of Math.random() with N. The next number would be N minus your result from the subtraction of N and the previous result.

final int N = 20;
final int result0 = (int) (Math.random() * N);
final int result1 = (int) (Math.random() * (N - result0));
final int result2 = N - result0 - result1;

EDIT: You could than choose the first, second and third parameter randomly too.

Related Topics

Leave a reply