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 操作。
輸出結果: