用Java实现:创建一个长度为n的随机字符串字符串,统计该字符串中每个字符出现的次数,并输出
时间: 2024-05-12 08:20:32 浏览: 49
以下是用Java实现的代码:
```
import java.util.HashMap;
import java.util.Random;
public class RandomString {
public static void main(String[] args) {
int n = 10; // 字符串长度为10
String str = generateRandomString(n);
System.out.println("随机字符串为:" + str);
HashMap<Character, Integer> map = countCharacters(str);
System.out.println("每个字符出现的次数为:");
for (Character c : map.keySet()) {
System.out.println(c + ": " + map.get(c));
}
}
public static String generateRandomString(int n) {
String str = "";
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
for (int i = 0; i < n; i++) {
int index = random.nextInt(charSet.length());
str += charSet.charAt(index);
}
return str;
}
public static HashMap<Character, Integer> countCharacters(String str) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
} else {
map.put(c, 1);
}
}
return map;
}
}
```
程序运行结果示例:
```
随机字符串为:Jf9X9KjJx8
每个字符出现的次数为:
f: 1
8: 1
K: 1
9: 2
x: 1
J: 2
j: 1
X: 1
```
阅读全文