Java 生成 4 位随机数字字符串
以下是使用 Java 代码生成一个包含 4 个数字的随机字符串的示例:
import java.util.Random;
public class RandomStringGenerator {
public static void main(String[] args) {
char[] chs = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
Random random = new Random();
char[] result = new char[4];
for (int i = 0; i < 4; i++) {
int index = random.nextInt(chs.length);
result[i] = chs[index];
}
System.out.println(new String(result));
}
}
代码解释:
- 定义字符数组 chs:包含数字 '0' 到 '9',用于生成随机字符串的字符来源。
- 创建 Random 对象:用于生成随机数。
- 定义 char 数组 result:长度为 4,用于存储生成的随机字符串。
- 使用 for 循环:循环 4 次,每次循环:
- 生成一个 0 到 chs 数组长度-1 之间的随机数 index。
- 将 chs[index] 赋值给 result[i]。
- 将 result 转换为 String 类型并输出。
此代码将生成一个包含 4 个数字的随机字符串,例如 '3821' 或 '9150'。
原文地址: https://www.cveoy.top/t/topic/nqxW 著作权归作者所有。请勿转载和采集!