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/[deleted] 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

u/[deleted] 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 on Double, there's no matching method that would make sense.