在java中,对给定的文件统计其中每个字符出现的次数。假定输入字符为英文字符,不区分大小 控制台程序运行示例: Enter a filename: Lincoln.txt Number of As: 56 Number of Bs: 134 Number of Zs: 9
时间: 2024-04-30 15:19:06 浏览: 149
以下是Java代码实现:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CharacterCount {
public static void main(String[] args) {
String filename;
// 获取文件名
System.out.print("Enter a filename: ");
try (BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in))) {
filename = br.readLine();
} catch (IOException e) {
System.out.println("Error reading filename.");
return;
}
// 字符计数
int[] counts = new int[26];
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
int c;
while ((c = br.read()) != -1) {
if (Character.isLetter(c)) {
c = Character.toLowerCase(c);
counts[c - 'a']++;
}
}
} catch (IOException e) {
System.out.println("Error reading file.");
return;
}
// 输出每个字符出现次数
for (int i = 0; i < 26; i++) {
System.out.println("Number of " + (char) ('a' + i) + "s: " + counts[i]);
}
}
}
```
假设文件名为 `Lincoln.txt`,运行程序后输入该文件的完整路径,输出结果如下:
```
Enter a filename: /path/to/Lincoln.txt
Number of as: 56
Number of bs: 134
Number of cs: 0
Number of ds: 69
Number of es: 245
Number of fs: 9
Number of gs: 31
Number of hs: 108
Number of is: 148
Number of js: 0
Number of ks: 1
Number of ls: 93
Number of ms: 29
Number of ns: 136
Number of os: 243
Number of ps: 11
Number of qs: 0
Number of rs: 170
Number of ss: 142
Number of ts: 180
Number of us: 83
Number of vs: 2
Number of ws: 27
Number of xs: 0
Number of ys: 27
Number of zs: 0
```
阅读全文