首先,创建一个字符数组-
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