Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - getting a random number from 100 to 999 [duplicate]

Tags:

java

Please tell me whether I am correct or not with the following line.

int x = ((int)(Math.random() * 100000)) % 1000;

This line always give me a 3 digit number 100 to 999 ?

Is there an easier way to type this out? Did I over complicate this code?

like image 873
Jaaavaaaaa Avatar asked Sep 12 '15 02:09

Jaaavaaaaa


People also ask

How do you prevent duplicate random numbers in Java?

The correct approach is to use “Math. random()”- to create random numbers and to avoid repetition we can use a hashset to achieve that.

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

Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.


3 Answers

There's a better way to get random numbers, and that's with java.util.Random. Math.random() returns a double (floating-point) value, but based on your request of a 3-digit number, I'm going to assume that what you really want is an integer. So here's what you do.

// initialize a Random object somewhere; you should only need one
Random random = new Random();

// generate a random integer from 0 to 899, then add 100
int x = random.nextInt(900) + 100;
like image 113
Ben M. Avatar answered Oct 07 '22 18:10

Ben M.


You are not correct. That can produce numbers under 100. The most familiar way is random.nextInt(900)+100. Here random is an instance of Random.

Before Java 7 there was no reason to create more than one instance of Random in your application for this purpose. Now there's no reason to have any, as the best way is

int value = ThreadLocalRandom.current().nextInt(100, 1000);
like image 4
Paul Boddington Avatar answered Oct 07 '22 17:10

Paul Boddington


Math.random() returns value between 0.0(including) and 1.0(excluding) say it returns 0.05013371.. (for example) than your method will do the following operation,

0.05013371.. * 100000 = 5013.371...
(int) 5013.371... = 5013
5013 % 1000 = 13 // Incorrect

But other way around you can still use Math.random() in a different way to solve this,

int upperBound = 999;
int lowerBound = 100;
int number = lowerBound + (int)(Math.random() * ((upperBound - lowerBound) + 1));

Explanation,

100 + (int)((Number >= 0.0 and  < 1.0) * (999 - 100)) + 1;
100 + (int)((Number >= 0.0 and  < 1.0) * (899)) + 1;

MIN This can return,

100 + (int)(0.0 * (899)) + 1;
100 + 0 + 1
101

MAX This can return,

100 + (int)(0.9999.. * (899)) + 1;
100 + 898 + 1 
999

NOTE : You can change upper and lower bound accordingly to get required results.

like image 3
akash Avatar answered Oct 07 '22 17:10

akash