A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© li--yong 中级黑马   /  2016-8-11 23:44  /  473 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.util.Random;

public class T {

        public static void main(String[] args) {
                String verift = getVerify();
                System.out.println(verift);
        }

        /**
         * 随机生成验证码
         *
         * @return
         */
        public static String getVerify() {

                char[] all = { '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 s = "";
                for (int i = 0; i < 4; i++) {
                        char r = all[random.nextInt(all.length)];
                        s+=r;
                }

                return s;
               
        }
}

评分

参与人数 1黑马币 +10 收起 理由
晓寒轻 + 10 很给力!

查看全部评分

5 个回复

倒序浏览
不错,继续加油
回复 使用道具 举报
x55555lg 来自手机 中级黑马 2016-8-17 22:25:09
藤椅
顶一个,支持一下
回复 使用道具 举报
想了下用正则生成,但是感觉好像不行,正则一般用于判断。然后用随机数产生合法的ascii码值来生成。通过一个随机数控制该位是大写字母、小写字母还是数字,
没有使用先生成ascii码再提取有效字符以提高效率。
[Java] 纯文本查看 复制代码
package demos;

import java.util.Random;

/*
 生成随机的四位验证码:0-9,a-z,A-Z
 */
public class Demo3 {
	public static final int NUM = 4;

	public static void main(String[] args) {
		for (int i = 1; i <= 100; i++) {
			System.out.print(getVerify() + "  ");
			if (i % 10 == 0) {
				System.out.println();
			}
		}
	}

	public static String getVerify() {
		String rs = "";
		Random ascii = new Random();
		for (int i = 0; i < NUM; i++) {
			int judge = ascii.nextInt(90) + 1;
			if (judge <= 30) {
				rs += (char) (ascii.nextInt(10) + 48);
			} else if (judge <= 60) {
				rs += (char) (ascii.nextInt(26) + 65);
			} else {
				rs += (char) (ascii.nextInt(26) + 97);
			}
		}
		return rs;
	}
}
回复 使用道具 举报
66666666666666666
回复 使用道具 举报
继续加油..........
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马