HeadFirstJava学习心得——随机字符串的产生

本文探讨了如何使用Java生成随机字符串,首先通过从预定义的字符串数组中随机拼接形成新字符串作为示例,然后详细介绍了如何从字典中随机选择单词,并提供了两种不同的实现方式。最后,讨论了如何生成定长的随机字符串,展示了类似验证码的随机字符生成方法,这些方法涉及到Unicode码的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个很有趣的例子:该程序从3个字符串数组中随机从3个字符串数组中任意取一部分拼接成新的字符串:
public class RandomString {

	public static void main(String[] args) {
		String[] wordListOne = { "24/7", "MultiTier", "30,000 foot", "B-to-B",
				"win-win", "font-end", "web-based", "pervasive", "smart",
				"six-sigma", "critical-path", "dynamic" };
		String[] wordListTwo = { "empowered", "sticky", "value-added",
				"oriented", "centric", "distributed", "clustered", "branded",
				"outside-the-box", "positioned", "networked", "focused",
				"leveraged", "aligned", "targeted", "shared", "cooperative",
				"accelerated" };
		String[] wordListThree = { "process", "tipping-point", "solution",
				"architecture", "core competency", "strategy", "mindshare",
				"portal", "space", "vision", "paradigm", "mission" };
		
		int oneLength = wordListOne.length;
		int twoLength = wordListTwo.length;
		int threeLength = wordListThree.length;

		int rand1 =(int) (Math.random()*oneLength);
		int rand2 =(int) (Math.random()*twoLength);
		int rand3 =(int) (Math.random()*threeLength);
		
		//组合专家术语
		String phrase = wordListOne[rand1] +" "+ wordListTwo[rand2] +" "+ wordListThree[rand3];
		System.out.println("What we need is a:"+phrase);
	}

}

以上程序的执行结果是:


根据以上思想,我们可以修改得到随机从字典中取一个单词的方法:

step1:将词典看做一个数组,数组中保存了一个个的单词;

step2:取得字典中单词的个数N,也就是数组的长度;

step3:从0~N-1中任意获取一个序号(产生0~N-1的随机数),再根据序号找到这个单词。


下面的代码是上述算法的实现;

public class RandomString2 {

	public static void main(String[] args) {

		// Step1:将单词保存到一个字符串数组中
		String[] wordList = { "process", "tipping-point", "solution",
				"architecture", "core competency", "strategy", "mindshare",
				"portal", "space", "vision", "paradigm", "mission" };

		// Step2:得到数组的长度
		int length = wordList.length;

		for (int i = 0; i < wordList.length; i++) {
			// Step3:产生0~length-1的随机数
			int randIndex = (int) (Math.random() * length);

			// Step4:根据随机序号给出单词
			System.out.println("随机找出的单词是:" + wordList[randIndex] + ";在词典中的位置是"
					+ randIndex);
		}

	}

}


现在思考这样一个问题:如何随机生成一个字符串(该字符串定长)呢?

我们可以采用以下思路:

step1:声明一个字符数组,数组的长度为需要生成的随机字符串的长度;

step2:使用一个循环为char数组赋值;

step3:使用String的String(char[] value)将char数组转化成String。

实现一:

public class RandomString3 {

	public static void main(String[] args) {
		char[] arr = new char[5];
		for (int i = 0; i < 5; i++) {
		    arr[i] =(char)((int) Math.abs(Math.random()*(90-65)+65));//为数组元素赋值
		}
                String objStr = new String(arr);
                System.out.println(objStr);
       }
}

以上程序生成了一个长度为5的大写字母组成的字符串。
实现二:

public class RandomString3 {
	public static void main(String[] args) {
		String wordList = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 		char[] arr = new char[5];
	    int len = wordList.length();
        for (int i = 0; i < 5; i++) {
			int randIndex = (int) (Math.random()*len); 
			arr[i] = wordList.charAt(randIndex);
		}
		String objStr = new String(arr);
		System.out.println(objStr);
	}
}
实现二完成了大小写、数字中任意取从而构造出新的字符串,但是当我们的字符串长度改变的时候需要修改循环条件,可不可以将其单独封装成一个方法呢?

请看下面的代码(应用了单态设计模式):

实现三:

import java.util.Random;

public class RandomString3 {

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			System.out.println(RandomString.randomString(6));
		}
	}

}

class RandomString {
	private static Random randGen = null;
	private static char[] numbersAndLetters = null;

	/*此类的设计应用了单态设计模式*/
	public static final String randomString(int length) {
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789"+"abcdefghijklmnopqrstuvwxyz"
					+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(numbersAndLetters.length)];
		}
		return new String(randBuffer);
	}
}

以上程序将产生随机字符串的方法封装成了RandomString类的randomString静态方法,运行结果截图:

该程序的运行结果是不是很像我们每天登陆网站需要的验证码?

生成随机字符

每个字符都有一个唯一的十六进制数0~0xFFFF(0~65535)之间的Unicode码。生成一个随机字符就是使用下面的表达式表示从0到65535之间的一个随机整数:

(int) (Math.random() * 65535 + 1);// 产生[1,65535]的随机数

从上面得到启发:生成随机小写字符

(char) ('a' + Math.random() * ('z' - 'a' + 1));
· 推广--->产生任意[ch1,ch2]之间的字符:

(char) (ch1 + Math.random() * (ch2 - ch1 + 1));






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值