对比输入的验证码案例和用户名,密码验证码正确登录案例

📅 发布时间:2026/7/3 1:42:42 👁️ 浏览次数:
对比输入的验证码案例和用户名,密码验证码正确登录案例
对比验证码案例package com.sy.comd; import java.util.Random; import java.util.Scanner; // 验证码 public class Stringtext01 { public static void main(String[] args) { String doom Doom(4); // 对比用户输入的验证码是否正确 // 键盘录入 System.out.println(本次验证码是doom); Scanner sc new Scanner(System.in); for (int i 0; i 3; i) { System.out.println(请输入验证码); String next sc.next(); if (next.equals(doom)){ System.out.println(输入正确); break; }else { System.out.println(输入错误); } } } public static String Doom(int n){ String f1 ; // 定义一个验证码 String txt abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789; Random random new Random(); // new 随机数 for (int i 0; i n; i) { int i1 random.nextInt(txt.length()); f1 txt.charAt(i1); } return f1; } }用户名密码验证码全部正确登录案例package ocm.sy.yanzm; import java.util.Random; import java.util.Scanner; // 登陆验证用户名、密码、验证码校验 public class Stringtext02 { public static void main(String[] args) { Scanner sc new Scanner(System.in); // 1. 输入用户名和密码 System.out.println(请输入用户名); String username sc.next(); System.out.println(请输入密码); String password sc.next(); // 2. 生成并展示验证码 String verifyCode generateVerifyCode(4); System.out.println(验证码是 verifyCode); // 3. 验证码校验最多3次 boolean isVerifyCodeCorrect false; for (int i 0; i 3; i) { System.out.println(请输入验证码剩余 (3 - i) 次机会); String inputVerifyCode sc.next(); if (inputVerifyCode.equals(verifyCode)) { System.out.println(验证码输入正确); isVerifyCodeCorrect true; break; } else { System.out.println(验证码输入错误); // 最后一次错误时提示并终止程序 if (i 2) { System.out.println(验证码错误次数过多登录失败); sc.close(); return; } } } // 4. 验证码正确后校验用户名和密码最多3次重试 if (isVerifyCodeCorrect) { boolean isLoginSuccess false; for (int i 0; i 3; i) { if (checkUserInfo(username, password)) { System.out.println(用户名和密码正确欢迎进入); isLoginSuccess true; break; } else { System.out.println(用户名或密码错误剩余 (2 - i) 次机会); // 最后一次错误时提示 if (i 2) { System.out.println(用户名密码错误次数过多登录失败); } else { // 重新输入用户名密码 System.out.println(请重新输入用户名); username sc.next(); System.out.println(请重新输入密码); password sc.next(); } } } } sc.close(); } // 校验用户名和密码模拟固定账户用户名sb密码123 public static boolean checkUserInfo(String username, String password) { String correctUsername 小明; String correctPassword 123; return correctUsername.equals(username) correctPassword.equals(password); } // 生成指定长度的验证码字母数字 public static String generateVerifyCode(int length) { String verifyCode ; // 验证码字符库大小写字母数字 String codeSource abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789; Random random new Random(); for (int i 0; i length; i) { // 随机获取字符库中的索引 int randomIndex random.nextInt(codeSource.length()); // 拼接字符生成验证码 verifyCode codeSource.charAt(randomIndex); } return verifyCode; } }