随机输出验证码

题目要求写出可以自动生成验证码的程序,由于之前写了个随机生成计算题的程序,因此这个程序,我打算使用随机数解决。

验证码即是一个字符串,且验证码这个字符串的每个字符从大小写字母和数字里面取得。因此,我新建了一个字符数组,里面包含了全部的大小写字母和数字。并通过以随机数作为下标,获得此字符数组里面的字符,连接到字符串上,以此得到想要的随机字符串。

此程序可以指定得到验证码的位数和个数。

程序代码:

package 验证码;

import java.util.Date;

import java.util.Scanner;

import java.util.Random;

public class yanzhengma {

public static String getstring(int n){

String str="";

int a;

char ch;

char [] c= {'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 r=new Random();

for(int i=0;i<n;i++) {

a=r.nextInt(c.length-1)+1;

ch=c[a];

str=str+ch;

}

return str;

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner scan=new Scanner(System.in);

int weishu;

int geshu=0;

System.out.println("请输入想要得到的验证码的位数:");

weishu=scan.nextInt();

System.out.println("请输入想要得到的验证码的个数:");

geshu=scan.nextInt();

for(int i=0;i<geshu;i++) {

System.out.println(getstring(weishu));

}

}

}

猜你喜欢

转载自www.cnblogs.com/ruangongyouxi/p/9749929.html
今日推荐