Java实现生成随机字符
时间: 2023-11-14 21:22:25 浏览: 40
以下是Java实现生成随机字符的示例代码:
```java
import java.util.Random;
public class RandomCharGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final int LENGTH = 10;
public static void main(String[] args) {
String randomString = generateRandomString();
System.out.println(randomString);
}
private static String generateRandomString() {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < LENGTH; i++) {
int index = random.nextInt(CHARACTERS.length());
char randomChar = CHARACTERS.charAt(index);
sb.append(randomChar);
}
return sb.toString();
}
}
```
该程序定义了一个包含所有可能字符的字符串常量 `CHARACTERS` 和字符串长度常量 `LENGTH`。`generateRandomString()` 方法使用 `Random` 类生成随机数来选择 `CHARACTERS` 中的字符,并将其添加到 `StringBuilder` 中。最后,返回生成的随机字符串。在 `main()` 方法中,调用该方法并打印结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)