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