r/javahelp • u/Alaa13 • Nov 28 '19
Math.Random keeps generating the same Value
I'm generating a 12 digit number for a Credit card. it must be 12 digits but random. have this line for code here :
debitCardNumber = (int) (Math.random() * Math.pow(10,12));
But, it keeps generating this value over and over: 2147483647.
In addition its 10 digits and not 12!
27
u/evil_burrito Extreme Brewer Nov 28 '19
You're getting Max Int, which is the maximum value stored in a 32-bit number. You don't really want to multiply by 10^12, which is far larger than can be stored in an int.
What you want is to store the number as a string and generate each value separately, or, use bitwise rotation and addition. You can't store a 12-digit number in an int, anyway.
6
u/nerdyhandle Nov 29 '19
But if they absolutely have to store a 12 digit number they can store it as a
long.
1
1
u/radulfr2 Nov 29 '19
Just because I like streams, here's one way using the ints method of java.util.Random. The upper bound is exclusive, hence the +1.
String debitCardNumber = new Random().ints(12, '0', '9' + 1)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();1
u/Philboyd_Studge Nov 28 '19
Instead, generate 12 single random digits and concatenate them together.
1
1
Nov 28 '19 edited Nov 28 '19
Try Math.random().toString(10).substring(2, 14);
1
u/morhp Professional Developer Nov 29 '19
This is not a good solution and will also crash randomly.
1
Nov 29 '19
Explain that last part.
2
u/morhp Professional Developer Nov 29 '19 edited Nov 29 '19
Well, what happens if Math.random() by some weird chance returns exactly 0.5 for example? You will try to compute
"0.5".substring(2, 14)and that will fail because 14 isn't a valid index of that String.Apart from that, you can't call
toString(10)on a double, primitives don't have member methods, and even onDouble, there's no matching method that would make sense.
5
u/NautiHooker Software Engineer Nov 28 '19
you are casting it to an int. thats the max value for an signed 32 bit integer. try lowering the factor that u calculate with the pow function or use a datatype that is larger than an int (long comes to mind)