隨機四位字母數字驗證碼
阿新 • • 發佈:2018-11-14
package Java.Project; import java.util.Random; //隨機四位驗證碼 public class Random_code { public static void main(String[] args) { System.out.println(new Random_num().code()); } } class Random_num{ //產生隨機四位a驗證碼 public static String code(){ //驗證碼組成字元 char[] list={'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','0','1','2','3','4','5','6','7','8','9'}; //產生隨機類 Random random =new Random(); //產生可變字串 StringBuilder str = new StringBuilder(); //設定計數器,計算驗證碼位數 int count=0; while(true){ int index = random.nextInt(list.length); char temp=list[index]; if(str.indexOf(""+temp) == -1){ str.append(temp); count++; if(count == 4) break; } } return str.toString(); } }