r/javahelp • • 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

16 comments sorted by

View all comments

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();