更新時(shí)間:2021-05-18 10:22:48 來源:動力節(jié)點(diǎn) 瀏覽1765次
Java 隨機(jī)生成4位的隨機(jī)數(shù)測試類
@org.junit.Test
public void testRandom(){
String msg="您的注冊碼為%s,謝謝注冊!";
System.out.println("Math.random得到小數(shù)");
System.out.println(Math.round((Math.random()+1) * 1000));
System.out.println("Random");
System.out.println(new Random().nextInt(9999));
System.out.println("字符串前面補(bǔ)0的話就這樣String.format");
System.out.println(String.format("%04d",new Random().nextInt(9999)));
}
注意:Math.random()方法結(jié)果可能會是0,所以進(jìn)行了 +1 操作。
輸出結(jié)果:
Math.random得到小數(shù)
6644
Random
5413
字符串前面補(bǔ)0的話就這樣String.format
2714
以上就是動力節(jié)點(diǎn)小編介紹的"Java四位隨機(jī)數(shù)怎樣隨機(jī)生成",希望對大家有幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為您服務(wù)。
初級 202925
初級 203221
初級 202629
初級 203743