代码一:
把需要验证的字符串,字母,数字,以及汉字都可以,添加入char类型的数组即可,直接添加即可,不需要修改其余的代码。
- package cn.itcast.collection;
- import java.util.Random;
- import java.util.Scanner;
- public class Test2 {
- /**
- * 制作一个6位的不同字符的验证码
- 输出到控制台,用户输入,判断对还是错
- 6位不同的,数字,字母,汉字
- */
- public static void main(String[] args) {
- char[] ch = {'1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
- Random ra = new Random();
- Scanner sc = new Scanner(System.in);
- int x =ra.nextInt(ch.length+1);
- StringBuffer sb = new StringBuffer();
- for (int i = x; sb.length() < 6 ; ) {
- String s = String.valueOf(ch[x]);
- if(!sb.toString().contains(s))
- sb.append(ch[x]);
- x =ra.nextInt(ch.length+1);
- }
- System.out.println(sb);
- System.out.println("请输入验证码:");
-
- String in = sc.nextLine();
- if(in.equals(sb.toString()))
- System.out.println("验证码输入正确!");
- else
- System.out.println("验证码输入错误!");
-
- }
- }
复制代码
代码二:
把需要验证的字符串,字母,数字,以及汉字都可以,添加入String s,直接添加即可,不需要修改其余的代码。
- package cn.itcast.collection;
- import java.util.Random;
- import java.util.Scanner;
- /**
- * 制作一个6位的不同字符的验证码
- 输出到控制台,用户输入,判断对还是错
- 6位不同的,数字,字母,汉字
- */
- public class Test3 {
- public static void main(String[] args) {
- String s = "0123456789qwertyuiopasdfghjklzxcvbnm" ;
- Random ran = new Random();
- int num = ran.nextInt(s.length()+1);
- StringBuffer sb = new StringBuffer();
- Scanner sc = new Scanner(System.in);
- for (int i = num; sb.length() < 6; ) {
- String ss = String.valueOf(s.charAt(num));
- if(sb.indexOf(ss)==-1)
- sb.append(s.charAt(num));
- num = ran.nextInt(s.length()+1);
- }
- System.out.println("验证码:"+sb);
- System.out.println("请输入验证码:");
- if(sb.toString().equals(sc.nextLine()))
- System.out.println("验证码正确!");
- else
- System.out.println("验证码错误!");
-
- }
- }
复制代码
|