1

I am trying to generate a random 4-digit number using the Java Math.random method. The number must always be 4 digits, i.e., allow for results such as 0001, or 0023, or 0123 to be possible. However, the traditional Math.random method formula below only allows numbers less than 1000 to be 1, 23, or 123.

int i = (int)(Math.random()*10000); 

Is there a way to do this using math.random and/or loops? Thank you, in advance, for any suggestions.

I tried researching how to ensure the 4-digit number always has 4 digits, but all results seem to suggest using Random class, or min/max. I DO NOT want to use this random class or max/min code as I have not yet studied it yet.

David Brossard
  • 13,584
  • 6
  • 55
  • 88
Anne Bailly
  • 391
  • 3
  • 9

1 Answers1

3

Your problem here is not the Random class, but to pad the numbers which don't have 4 digits. Therefore you have to use a String instead of an int. You can pad the number by using String.format():

Random random = new Random();
int number = random.nextInt(10000);
String result = String.format("%04d", number);

This will ensure that your result String has always 4 digits.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56