Java之生成一个随机验证码(数字+大小写字母)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82024013

需求:设计一个方法,获得指定位数的验证码,验证码的内容可以包含数字和大小写字母

ex1:

public class Demo {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(getCode(4));//调用getCode()方法打印一个四位数的随机验证码结果
	}
	/*
	 * 定义一个获取随机验证码的方法:getCode();
	 */
	public static String getCode(int n) {
		String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//保存数字0-9 和 大小写字母
		char[] ch = new char[n]; //声明一个字符数组对象ch 保存 验证码
		for (int i = 0; i < n; i++) {
			Random random = new Random();//创建一个新的随机数生成器
			int index = random.nextInt(string.length());//返回[0,string.length)范围的int值    作用:保存下标
			ch[i] = string.charAt(index);//charAt() : 返回指定索引处的 char 值   ==》保存到字符数组对象ch里面
		}
		//将char数组类型转换为String类型保存到result
		//String result = new String(ch);//方法一:直接使用构造方法      String(char[] value) :分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
		String result = String.valueOf(ch);//方法二: String方法   valueOf(char c) :返回 char 参数的字符串表示形式。
		return result;
	}
	
}

运行结果图:(注意:这仅仅只是  随机生成一个四位数验证码  所截的图)

ex2:

public class Demo {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(getCode(4));//调用getCode()方法打印一个四位数的随机验证码结果
	}
	/*
	 * 定义一个获取随机验证码的方法:getCode();
	 */
	public static String getCode(int n) {
		String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//保存数字0-9 和 大小写字母
		StringBuffer sb = new StringBuffer(); //声明一个StringBuffer对象sb 保存 验证码
		for (int i = 0; i < n; i++) {
			Random random = new Random();//创建一个新的随机数生成器
			int index = random.nextInt(string.length());//返回[0,string.length)范围的int值    作用:保存下标
			char ch = string.charAt(index);//charAt() : 返回指定索引处的 char 值   ==》赋值给char字符对象ch
			sb.append(ch);// append(char c) :将 char 参数的字符串表示形式追加到此序列  ==》即将每次获取的ch值作拼接
		}
		return sb.toString();//toString() : 返回此序列中数据的字符串表示形式   ==》即返回一个String类型的数据
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82024013