1. 程式人生 > 其它 >Try with Resources

Try with Resources

public static void main(String[] args) {
//2、呼叫獲取驗證碼的方法,將得到的驗證碼輸出到控制檯
while (true){
String checkCode = getCheckCode();
System.out.println("當前驗證碼:"+checkCode);
//3、通過鍵盤錄入獲取使用者輸入的驗證碼
System.out.println("請輸入:");
Scanner sc=new Scanner(System.in);
String userInput=sc.nextLine();
//4、比較使用者輸入的和鍵盤錄入的驗證碼是否匹配,這裡使用忽略大小寫比較
if (checkCode.equalsIgnoreCase(userInput)){
//4.1、匹配正確,給出提示資訊,結束迴圈
System.out.println("驗證通過..");
break;
}else {
System.out.println("驗證失敗..");
}
}
}
//1、定義一個方法,專門用來生成驗證碼
public static String getCheckCode(){
//1.1 定義一個字串表示大寫字母所有取值範圍
String upCode="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//1.2 將大寫字母對應的字串呼叫toLowerCase()得到所有小寫字母取值範圍
String lowerCode=upCode.toLowerCase();
//1.3 定義一個字串表示所有數字取值範圍
String numberCode="0123456789";
//1.4 定義一個StringBuilder變數 sb,用於將所有字元拼接到一起
StringBuilder sb=new StringBuilder(upCode);
sb.append(lowerCode).append(numberCode);
String allCode=sb.toString();
//1.5 重新定義一個StringBuilder變數 sb1,用來拼接驗證碼
StringBuilder sb1=new StringBuilder();
//1.6 迴圈四次,每次從sb中取一個隨機字元
Random r=new Random();
for (int i = 0; i < 4; i++) {
//使用Random生成隨機索引
int index=r.nextInt(allCode.length());
//獲取隨機索引位置對應的字元
char ch=allCode.charAt(index);
//將獲取到的字元拼接到sb1中
sb1.append(ch);
}
//1.7 將sb1轉為字串並返回
return sb1.toString();
}