When math. Random () is used to generate a 6-digit random number, the problem is solved, and a 6-digit random number is obtained successfully.

Source: Internet
Author: User

Recently, when I was working as a health bureau examination network, I needed to implement the function of sending a verification code via SMS. Therefore, I had to use the function of randomly generating 6-digit verification codes, write a random

int i=(int)(Math.random()*1000000+100000); 
String messageCode = String.valueOf(i);

After the test was sent, a 6-digit random number was sent, and thought it was correct. However, during subsequent tests, it was suddenly found that the verification code sometimes had 7 digits, then you can check the code,

Math. Random () generates a random number of doule numbers between 0.0 and 1.0.

No way to test. Write a main function to generate 100 random numbers.

public static void main(String[] args) {
for(int j = 0; j< 100; j++){
int i=(int)(Math.random()*1000000+100000);
String messageCode = String.valueOf(i);
System.out.println(messageCode);

}
}

It turns out that there are both 6 and 7 random numbers. It's strange, how is it different from your own intention? Then, I tested it directly.

public static void main(String[] args) {
for(int j = 0; j< 100; j++){
System.out.println((Math.random()));
}
}

The generated random number is 0.0xxx. I am confused. I checked the document and finally realized that the random number should be 0. 0000... -1. 00000... between,

The first digit, which is not 0, is located after the decimal point.

Then, we can only re-Trust the method based on the test results. The test is true.

public static void main(String[] args) {
for(int j = 0; j< 100; j++){
System.out.println((int)((Math.random()*9+1)*100000));
}
}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.