Java 输出HelloWorld中每个字母出现的次数
时间: 2024-09-17 18:06:05 浏览: 31
在Java中,你可以通过创建一个HashMap来跟踪每个字符及其出现的次数。下面是一个简单的示例程序,它遍历`HelloWorld`字符串并统计每个字符的频率:
```java
import java.util.HashMap;
import java.util.Map;
public class HelloWorldCount {
public static void main(String[] args) {
String str = "HelloWorld";
Map<Character, Integer> charCountMap = new HashMap<>();
// 遍历字符串中的每个字符
for (char c : str.toCharArray()) {
// 如果字符已经在map中,则增加计数
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1);
} else { // 否则添加新的键值对,初始计数为1
charCountMap.put(c, 1);
}
}
// 打印每个字符及其出现次数
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println("Character '" + entry.getKey() + "' appears " + entry.getValue() + " times");
}
}
}
```
运行这个程序,你会看到输出类似这样的信息:
```
Character 'H' appears 1 times
Character 'e' appears 1 times
Character 'l' appears 3 times
Character 'o' appears 2 times
Character 'W' appears 1 times
Character 'r' appears 1 times
Character 'd' appears 1 times
```
阅读全文