Java學習筆記
今天寫一個隨機生成n位的驗證碼,包含字母大小寫和數字,直接見代碼。
package com.itheima.hello;// 生成一個隨機位數的驗證碼
public class ScannerDemo1 {public static void main(String[] args){System.out.println(getCode(4));System.out.println(getCode(6));}public static String getCode(int n){String code="";for(int i=0;i<n;i++){int type=(int)(Math.random()*3); // 0,1,2switch (type){case 0:int t=(int)(Math.random()*10);code += t;break;case 1:int tt=(int)(Math.random()*26);char c=(char)('A'+tt);code += c;break;case 2:int ttt=(int)(Math.random()*26);char cc=(char)('a'+ttt);code += cc;break;}}return "隨機生成的"+n+"驗證碼為: "+code;}
}
運行結果如下 :
隨機生成的4驗證碼為: 7Q33
隨機生成的6驗證碼為: 0FIiwD