以下是Java代码实现:

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对象,用于生成随机数。接着定义一个长度为4的char数组result,用于存储生成的随机字符串。使用for循环,每次循环生成一个0到chs数组长度-1之间的随机数index,然后将chs[index]赋值给result[i]。最后将result转为String类型并输出即可

生成一个4位随机字符串字符来源于chs数组public char chs = 0 1 2 3 4 5 6 7 8 9;

原文地址: https://www.cveoy.top/t/topic/cazU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录