10

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jaaavaaaaa
  • 163
  • 1
  • 2
  • 5

5 Answers5

26

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;
Ben M.
  • 2,370
  • 1
  • 15
  • 23
5

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);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
3

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.

akash
  • 22,664
  • 11
  • 59
  • 87
1

There is a bug in the code. It can return numbers less than 100 as well. The following link Math.random() explained has the solution.

Community
  • 1
  • 1
Kiran Indukuri
  • 402
  • 3
  • 9
0

I don't think what you did here is appropriate. You should create a Random object instead.

Random random = new Random();
int randomNumber = random.nextInt(900) + 100;

Now randomNumber must be three digit.

I wrote a program to test whether your method is correct:

int x = 0;
int count = 0;
do {
    x = ((int)(Math.random() * 100000)) % 1000;
    count++;
} while (Integer.toString(x).length() == 3);
System.out.println ("Finished after " + count + " tries");

And it says "Finished after 4 tries", which means that your method is not correct.

Sweeper
  • 213,210
  • 22
  • 193
  • 313