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?
The correct approach is to use “Math. random()”- to create random numbers and to avoid repetition we can use a hashset to achieve that.
Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.
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;
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With