0

I want to generate a six-digit random number everytime. I am using

public class Test {
    static Random rand = new Random();

    
    public static void main(String[] args) {

        int rand_int1 = rand.nextInt(1000000);
        System.out.println(rand_int1);

Will it print the six-digit number or it can print any number between 0 to 1000000. I executed and got a 6 digit number but just want to be sure Can it give 1 or 2 or 3 digit number also?

  • Depends what you mean by a "6 digit number". Is "0" a six digit number, just missing the leading zeros when you print it? Or do you mean it starts with 1-9, followed by 5 0-9 digits? If the latter, you need to generate a number between 100000 and 1000000. – Andy Turner Sep 07 '20 at 10:20
  • You could very easily test this yourself, and see that it produces numbers with less than six digits. I ran it a few thousand times by wrapping it in a loop and among others I got numbers like 6642, 40328, etc. – JustAnotherDeveloper Sep 07 '20 at 10:22
  • @JustAnotherDeveloper you'd surely only need to run it a few times: I'd expect a non-6 digit number about 10% of the time. – Andy Turner Sep 07 '20 at 10:22
  • @Andy Turner yes i need the latter one between 100000 and 999999.How can i get that? –  Sep 07 '20 at 10:23
  • @AndyTurner Yeah, I know. It's just the value I put in the loop. Could have been in the hundreds and still produce a few of those easily. – JustAnotherDeveloper Sep 07 '20 at 10:24
  • @Johnson see one of the 90 answers in the duplicate. – Andy Turner Sep 07 '20 at 10:26
  • Yes just checked int min =100000; int max = 999999; int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); System.out.println(randomNum); This works –  Sep 07 '20 at 10:29

0 Answers0