编写一个java程序,随机生成一个长度为n(n>3)的字符串(字符串只包含小写字母),统计该字符串每个字符出现的次数,并输出
时间: 2024-05-25 12:15:50 浏览: 76
以下是一个Java程序,可以随机生成一个长度为n(n>3)的字符串,统计该字符串每个字符出现的次数,并输出:
import java.util.*;
public class CountCharOccurrences {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of the string (n > 3): ");
int n = input.nextInt();
while (n <= 3) {
System.out.print("Invalid input! Please enter a number greater than 3: ");
n = input.nextInt();
}
String str = generateRandomString(n);
System.out.println("Randomly generated string: " + str);
Map<Character, Integer> charOccurrences = countCharOccurrences(str);
System.out.println("Number of occurrences of each character:");
for (char c : charOccurrences.keySet()) {
System.out.println(c + ": " + charOccurrences.get(c));
}
}
public static String generateRandomString(int n) {
Random random = new Random();
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
char c = (char) (random.nextInt(26) + 'a');
sb.append(c);
}
return sb.toString();
}
public static Map<Character, Integer> countCharOccurrences(String str) {
Map<Character, Integer> charOccurrences = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (charOccurrences.containsKey(c)) {
charOccurrences.put(c, charOccurrences.get(c) + 1);
} else {
charOccurrences.put(c, 1);
}
}
return charOccurrences;
}
}
阅读全文