Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate short random number in java?

Tags:

java

random

short

I want to generate a random number of type short exactly like there is a function for integer type called Random.nextInt(134116). How can I achieve it?

like image 347
waqas Avatar asked Apr 17 '12 09:04

waqas


People also ask

How do you generate a random number from 1 to 5 in Java?

Java Random number between 1 and 10 Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand != 0) break; } System.

How do you generate a 3 digit random number in Java?

You should create a Random object instead. Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.


3 Answers

There is no Random.nextShort() method, so you could use

short s = (short) Random.nextInt(Short.MAX_VALUE + 1);

The +1 is because the method returns a number up to the number specified (exclusive). See here

This will generate numbers from 0 to Short.MAX_VALUE inclusive (negative numbers were not requested by the OP)

like image 114
luketorjussen Avatar answered Oct 15 '22 20:10

luketorjussen


The most efficient solution which can produce all possible short values is to do either.

short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short

or even faster

class MyRandom extends Random {
    public short nextShort() {
        return (short) next(16); // give me just 16 bits.
    }
    public short nextNonNegativeShort() {
        return (short) next(15); // give me just 15 bits.
    }
}

short s = myRandom.nextShort();
like image 38
Peter Lawrey Avatar answered Oct 15 '22 20:10

Peter Lawrey


Java shorts are included in the -32 768 → +32 767 interval.

why wouldn't you perform a

Random.nextInt(65536) - 32768

and cast the result into a short variable ?

like image 11
Skippy Fastol Avatar answered Oct 15 '22 19:10

Skippy Fastol