用java写一个生成4位随机数字加字符串的代码
时间: 2024-05-12 15:17:20 浏览: 114
可以使用java.util.Random类生成4位随机数字,再使用StringBuilder类生成字符串,将两个字符串拼接即可。以下是示例代码:
```
import java.util.Random;
public class RandomCode {
public static void main(String[] args) {
String randomCode = generateRandomCode();
System.out.println(randomCode);
}
public static String generateRandomCode() {
Random rand = new Random();
int codeNum = rand.nextInt(9000) + 1000; // 生成4位随机数字
StringBuilder codeStr = new StringBuilder();
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (int i = 0; i < 4; i++) { // 生成4位随机字符串
int index = rand.nextInt(str.length());
char c = str.charAt(index);
codeStr.append(c);
}
return codeNum + codeStr.toString();
}
}
```
阅读全文
相关推荐


















