随机数及随机字符串

示例1:产生随机数

public static void main(String[] args) { // 产生随机三位整数[100,999]
	// 方式一:
	// Math.random()产生随机[m,n]整数的公式:Math.random()*(n-m+1)+m
	for (int i = 0; i < 10; i++) {
		int digit = (int) (Math.random() * 900 + 100);
		System.out.println(digit);
	}
	// 方式二:
	// Random#nextInt()产生随机[m,n]整数的公式:random.nextInt(n-m+1)+m
	Random random = new Random();
	for (int i = 0; i < 10; i++) {
		int digit = random.nextInt(900) + 100;
		System.out.println(digit);
	}
}

示例2:产生随机字符串

public static void main(String[] args) {	//产生随机字符串
	for(int i =0;i<10;i++) {
		String str = UUID.randomUUID().toString();
		System.out.println(str);
	}
	//产生长度是15的,不包含-的随机字符串
	String res1 = UUID.randomUUID().toString().replaceAll("-", "").substring(3,19);
	System.out.println(res1);
	
	//产生长度为12的随机字符串,要求第一个是小写字母,第2到第5个是数字,
	//其余的可以是小写字母、大写字母或数字
	char[] source = {'0','1','2','3','4','5','6','7','8','9',
			'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
			'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	Random random = new Random();
	
	String res2 = "";
	int index = random.nextInt(27)+10;
	res2+=source[index];//第一个是小写字母
	for(int i =0;i<4;i++) {//第2到第5个是数字
		index = random.nextInt(9);
		res2+=source[index];
	}
	for(int i =0;i<7;i++) {//其余的
		index = random.nextInt(61);
		res2+=source[index];
	}
	System.out.println(res2);
}
发布了253 篇原创文章 · 获赞 666 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/lianghecai52171314/article/details/103814943