Java 程序生成随机数字字符串
首先,创建一个字符数组 −
static char num[] = { '0', '1', '2', '3', '4', '5' };
现在,假设你想要一个指定长度的字符串。创建一个 StringBuilder 并使用 append() 从中创建随机数字字符串 −
int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); }
以上,我们创建了一个返回随机数字字符串的 randomNum() 函数 −
public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; }
示例
public class Demo { static char num[] = { '0', '1', '2', '3', '4', '5' }; public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; } public static void main(String[] args) { int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); } System.out.println("Random numbers string = "+strBuilder.toString()); } }
输出
Random numbers string = 23024
广告