题目:17.16 (字符的頻率)
编写一个程序,提示用户输入一个 ASCII 文本文件名,然后显示文件中每个字符出现的频率。
-
代码示例
编程练习题17_16FrequencyOfCharacters.java
package chapter_17;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
public class 编程练习题17_16FrequencyOfCharacters {
public static void main(String[] args) {
int[] ascii = new int[128];
Scanner in = new Scanner(System.in);
System.out.print("Enter a ASCII text file name:");
String path = in.next().replaceAll("\\\\", "/");
in.close();
if(!path.isEmpty()) {
File file = new File(path);
try (
DataInputStream input = new DataInputStream(new FileInputStream(file));
){
int nextChar;
while((nextChar = input.read()) != -1) {
ascii[nextChar]++;
}
}catch (Exception e) {
e.printStackTrace();
}
}
for(int i = 0; i < 128;i++) {
if(ascii[i] != 0)
System.out.println((char)i + " appeared "+ascii[i]+" times.");
}
}
}
-
结果展示
Enter a ASCII text file name:C:\Users\Lenovo\eclipse-workspace\JavaFX\src\Text\Exercise17_16.txt
a appeared 2 times.
b appeared 2 times.
c appeared 2 times.
d appeared 2 times.
e appeared 2 times.
f appeared 2 times.
g appeared 2 times.