java 隨機生成4位隨機數


java 隨機生成4位的隨機數測試類

@org.junit.Test
public void testRandom(){
String msg="您的注冊碼為%s,謝謝注冊!";

System.out.println("Math.random得到小數");
System.out.println(Math.round((Math.random()+1) * 1000));
System.out.println("Random");
System.out.println(new Random().nextInt(9999));
System.out.println("字符串前面補0的話就這樣String.format");
System.out.println(String.format("%04d",new Random().nextInt(9999)));
}

注意:Math.random()方法結果可能會是0,所以進行了 +1 操作。

 輸出結果:

Math.random得到小數

6644
Random
5413
字符串前面補0的話就這樣String.format
2714


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM