Java基于给定代码框架按规则实现8位随机密码生成
基于现有Java框架的8位随机密码实现
实现逻辑
严格按照给定的抽取规则生成总长度为8位的密码,各部分字符来源、占比完全匹配要求:
- 从用户输入的first name中随机抽取3个字母
- 从用户输入的last name中随机抽取2个字母
- 从用户输入的手机号中随机抽取2位数字
- 从预置的
specialChar特殊字符集中随机抽取1个字符 - 所有抽取到的字符拼接即为最终密码
实现时使用JDK自带的Random类生成随机索引,索引范围严格匹配对应来源字符串的长度,不会出现索引越界问题。即使用户输入的名、姓长度较短,也能通过随机重复抽取满足固定数量要求。
完整可运行代码
import java.util.Scanner; import java.util.Random; public class testingstring { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); Random random = new Random(); String specialChar = "!@#$%^&*()"; System.out.println("Enter your first name: "); String firstName = userInput.next(); System.out.println("Enter your last name: "); String lastName = userInput.next(); System.out.println("Enter your phone number: "); String phoneNum = userInput.next(); StringBuilder passwordBuilder = new StringBuilder(); // 从名字中抽取3个随机字符 for (int i = 0; i < 3; i++) { int idx = random.nextInt(firstName.length()); passwordBuilder.append(firstName.charAt(idx)); } // 从姓氏中抽取2个随机字符 for (int i = 0; i < 2; i++) { int idx = random.nextInt(lastName.length()); passwordBuilder.append(lastName.charAt(idx)); } // 从手机号中抽取2个随机数字 for (int i = 0; i < 2; i++) { int idx = random.nextInt(phoneNum.length()); passwordBuilder.append(phoneNum.charAt(idx)); } // 从特殊字符集中抽取1个随机字符 int specialIdx = random.nextInt(specialChar.length()); passwordBuilder.append(specialChar.charAt(specialIdx)); System.out.println("生成的随机密码:" + passwordBuilder); userInput.close(); } }
注意事项
- 代码仅依赖JDK原生类,无额外第三方依赖,JDK 8及以上版本可直接编译运行
- 相同的用户输入信息,每次程序运行生成的密码均不相同,符合随机要求
- 最终生成的密码长度固定为8位,字符来源完全符合规则要求
内容的提问来源于stack exchange,提问作者Mesut Ozil
相关产品推荐
相关产品推荐

