现在的位置: 首页 > 综合 > 正文

java生成随机字母

2018年05月19日 ⁄ 综合 ⁄ 共 474字 ⁄ 字号 评论关闭

网上的方法

public class RandomTest extends TestCase {
	public void testRandom1() throws Exception {
		String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		char[] c = s.toCharArray();
		Random random = new Random();
		for( int i = 0; i < 8; i ++) {
			System.out.println(c[random.nextInt(c.length)]);
		}
	}
}

这个自己想的,后来发现网上也有很多人介绍

	public void testRandom2() throws Exception {
		Random random = new Random();
		for( int i = 0; i < 8; i ++) {
			int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写还是小写
			System.out.println((char)(choice + random.nextInt(26)));
		}
	}

 

抱歉!评论已关闭.