/**
 * 0:表示前面补0
 * lastLength:表示保留数字位数
 * d:表示参数为正数类型
 * start:需要格式化的数字
 */

// 前缀SY01,长度9
String prefix = "SY01";
Integer prefixLength = prefix.length();
Integer lastLength = 9 - prefixLength;

int start = 1;
for(int i = 1; i <10; i++){
	start ++;
	String last = String.format("%0" + lastLength + "d", start);
	System.out.println(prefix + last);
}

/*SY0100002
SY0100003
SY0100004
SY0100005
SY0100006
SY0100007
SY0100008
SY0100009
SY0100010*/	

2、生成100以内的随机数

(int)(Math.random()*100+1)

3、生成5位数,不足前面补0

String.format("%05d",new Random().nextInt(99999-1));

StringUtils.leftPad("1", 5, "0"); // 00001 五位数,不足左边补0
StringUtils.right("100001", 5); // 00001 取最右边的5位数

4、生成3位数随机数

new Random().nextInt(999-100)+100;

System.out.println((new Random().nextInt(8999) + 1000));  // 随机4位数
System.out.println((new Random().nextInt(899999) + 100000)); // 随机6位数

5、生成6位随机数

String.valueOf((int) ((Math.random() * 9 + 1) * 100000))

6、hutool工具类

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.2.3</version>
</dependency>

RandomUtil.randomNumbers(6);

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐