0730作业2:随机生成6位的字符串验证码,要求包含数字、大小写字母
package cn.meiju; public class Password { public static void main(String[] args) {
//输入需要的数字约之母 char[] arr = {48,49,50,51,52,53,54,55,56,57,//从0到9的数字 65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,//从A到Z的数字 97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122//从a到z的数字 }; int i=1; while(i++<=6){ //循环六次,得到六位数的验证码 char msg =arr[(int)(Math.random()*62)]; System.out.print(msg); } } }
网上方法2:
import java.util.Random; /* * 包好了二十六个字母和十个数字的字符数组 * @param Length 需要的字符长度 * @return 返回随机字母数字组合字符串 */ public class AllCharacter { public static String getName(int length) { String val = ""; Random random = new Random(); //参数length,表示生成几位随机数 for (int i = 0; i < 6; i++) { //随机数由0-9,a-z,A-Z组成,数字占10个,字母占52个,数字、字母占比1:5(标准的应该是10:52) //random.nextInt(6) 0-5中6个数取一个 String charOrNum = (random.nextInt(6)+6) % 6 >=1 ? "char" : "num"; //输出字母还是数字 if ("char".equalsIgnoreCase(charOrNum)) { //输出是大写字母还是小写字母,输出比例为1:1 int temp = random.nextInt(2) % 2 == 0 ? 97 : 65; //char(65)-char(90) 为大写字母A-Z;char(97)-char(122)为小写字母a-z val += (char) (random.nextInt(26) + temp); } else if ("num".equalsIgnoreCase(charOrNum)) { val += String.valueOf(random.nextInt(10)); } } return val; } }
老师的方法:
package com.homework; public class Password { public static String getCode(int length){ String code = ""; for(int i=0;i<length;i++){ boolean boo = (int)(Math.random()*2)==0; if(boo){ code += String.valueOf((int)(Math.random()*10)); }else { int temp = (int)(Math.random()*2)==0?65:97; char ch = (char)(Math.random()*26+temp); code += String.valueOf(ch); } } return code; } public static void main(String[] args) { System.out.println(Password.getCode(6)); System.out.println("-----------------"); System.out.println(Password.getVerify(6)); } public static String getVerify(int length){ String code = ""; String str = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASFGHJKLZXCVBNM"; String[] strs = str.split(""); for(int i = 0;i<length;i++){ code += strs[(int)(Math.random()*strs.length)]; } return code; } }