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!
16
Upvotes
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.