Java生成随机码(兑换码),带大小、小写字母、数字。

import java.util.Random;

public class RandomString {

	/***
	 * 产生随机数的方法
	 * 
	 * @param length
	 * @return
	 */
	public static String getCharAndNumr(int length) {
		if (length >= 3) {
			String val = "";
			Random random = new Random();
			// t0、t1、t2用来标识大小写和数字是否在产生的随机数中出现
			int t0 = 0;
			int t1 = 0;
			int t2 = 0;
			for (int i = 0; i < length; i++) {
				String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
				// 产生的是字母
				if ("char".equalsIgnoreCase(charOrNum)) // 字符串
				{
					// int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
					// //取得大写字母还是小写字母
					int choice = 0;
					if (random.nextInt(2) % 2 == 0) {
						choice = 65;
						t0 = 1;
					} else {
						choice = 97;
						t1 = 1;
					}
					val += (char) (choice + random.nextInt(26));
				}
				// 产生的是数字
				else if ("num".equalsIgnoreCase(charOrNum)) // 数字
				{
					val += String.valueOf(random.nextInt(10));
					t2 = 1;
				}
			}
			// 用于判断是是否包括大写字母、小写字母、数字
			if (t0 == 0 || t1 == 0 || t2 == 0) {
				val = getCharAndNumr(length); // 不满足则递归调用该方法
				return val;
			}

			else
				return val;

		} else {

			return null;
		}
	}

	/***
	 * 用来处理长度不符合要求的情况
	 * 
	 * @param rcs
	 * @return
	 */
	public static String tt(String rcs) {
		int lenth = 0;
		java.util.Scanner sc = new java.util.Scanner(System.in);
		String val = null;
		if (rcs == null) {
			System.out.println("重新输入字符串的长度,输入的长度要大于3");
			lenth = sc.nextInt();
			rcs = getCharAndNumr(lenth); // 调用随机数的方法
			val = tt(rcs); // 递归调用字符是否符合要求
		} else {
			val = rcs;
		}
		return val;
	}

	/****
	 * 主函数方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String rcs = getCharAndNumr(20); // 调用随机数的方法
		String val = tt(rcs); // 得到随机数
		System.out.println("随机数:" + val);

	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值