java 生成8位随机密码

该博客展示了如何使用Java编写一个生成8位包含大小写字母、数字和特殊字符的随机密码的方法。通过Random类和自定义switch语句,确保密码包含不同类型的字符,从而增加密码的复杂性和安全性。
package com.fastone.www.javademo.randomtest;

import java.util.Random;

/**
 * @program: javademo
 * @description: 生成8位随机密码
 * @author: sunyuhua
 * @create: 2021-11-25 12:43
 **/
public class CreateNewPassword {

	public static void main(String[] args) {
		System.out.println("==="+randomPassword());
	}

	private static final String SPECIAL_CHARS = "! @#$%^&*_=+-/";

	private static char nextChar(Random rnd){
		switch(rnd.nextInt(4)){
			case 0:
				return (char)('a'+rnd.nextInt(26));
			case 1:
				return (char)('A'+rnd.nextInt(26));
			case 2:
				return     (char)('0'+rnd.nextInt(10));
			default:
				return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
		}
	}
	public static String randomPassword(){
		char[] chars = new char[8];
		Random rnd = new Random();
		for(int i=0; i<8; i++){
			chars[i] = nextChar(rnd);
		}
		return new String(chars);
	}
}

输出结果(每一次都不一样):

11uL$=6V
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MonkeyKing.sun

对你有帮助的话,可以打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值