`

生成字母加数字的八位随机码

    博客分类:
  • JAVA
阅读更多
工作中遇到要生成八位字母加数字的随机码,代码如下:

	/**
	 * 生成数字加字母随机验证码
	 *
	 */
	@Test
	public void generateCode() {
		Random r=new Random();
		String code="";
		for(int i=0;i<8;++i){
			if(i%2==0){
				//产生随机整数0-9
				code+=r.nextInt(10);
			}else{
				//奇数产生随机字母包括大小写,65-90大写字母,97-122小写字母
				int temp=r.nextInt(52);
				char x=(char)(temp<26?temp+97:(temp%26)+65);
				code+=x;
			}
		}
		System.out.println(code);
	}

运行结果如下:
5C7o1x8s
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics