代码:
public class RandomNumUtil {
public static long getRandomCode(int size) { // 传入要生成的随机数的位数
double n = Math.pow(10, (size - 1));
int num;
if (size > 1) {
num = (int) (Math.random() * (9 * n) + n);
} else {
num = (int) (Math.random() * 10);
}
return num;
}
// 主函数测试
public static void main(String[] args) {
int size = 6;
long randomCode = getRandomCode(size); // 传入要生成的随机数的位数
System.out.println("随机生成的"+size+"位数为:"+randomCode);
}
}
效果图:
4位:
6位:
8位: