例1:统计一个文件a.txt中字母'A'和'a'出现的总次数
public class Test1 {
public static void main(String[] args) throws IOException {
try (
Reader r = new FileReader("a.txt")
) {
int kk=0;
int count=0;
while((kk=r.read())>-1){
if(kk=='A' || kk=='a')
count++;
}
System.out.printf("A或者a出现%d次",count);
}
}
}
例2:统计一个文件calcCharNum.txt中各个字母出现次数:A(8),B(16),C(10)...,a(12),b(10),c(3)....,括号内代表字符出现次数;
方法一:字典数组
public class Test2 {
public static void main(String[] args) throws Exception {
int[] daXie = new int[26];
int[] xiaoXie = new int[26];
try (
Reader r = new FileReader("a.txt")
) {
int kk = 0;
while ((kk = r.read()) > -1) {
if (kk >= 'A' && kk <= 'Z') {
daXie[kk - 'A']++;
}
if (kk >= 'a' && kk <= 'z')
xiaoXie[kk - 'a']++;
}
}
for (int i = 0; i < daXie.length; i++) {
if (daXie[i] > 0)
System.out.printf("%c(%d),", (char) (i + 'A'), daXie[i]);
}
System.out.println();
for (int i = 0; i < xiaoXie.length; i++) {
if (xiaoXie[i] > 0)
System.out.printf("%c(%d),", (char) (i + 'a'), xiaoXie[i]);
}
}
}
方法二:面向对象
1、定义一个类用于存储字符和该字符出现的次数
public class CharNum {
private final char chars;
private int number;
public CharNum(char chars) {
this.chars = chars;
this.number=1;
}
public char getChars() {
return chars;
}
public int getNumber() {
return number;
}
public void addNumber(){
this.number++;
}
@Override
public String toString() {
return chars + "(" + number + ')';
}
}
2、不能使用定长数组,需要自定义一种数据结构,可以按照需要进行变长
public class Collection { //具体的底层实现实际上还是采用数组,当然也可以使用链表的方式
private CharNum[] data;//具体存储数据的数组
private int pos;//记录当前数组中存储的数据个数
public void add(CharNum obj) {
if (data == null)
data = new CharNum[10];
boolean flag = false;
for (int i = 0; i < pos; i++) {
if (data[i] != null && data[i].equals(obj)) {
data[i].addNumber();
flag = true;
break;
}
}
if (!flag) {
if(pos>=data.length-1){
int len=data.length;
CharNum[] arr = new CharNum[len + len / 2]; //扩容比50%
for(int i=0;i<data.length;i++)
arr[i]=data[i];
this.data=arr;
}
data[pos++] = obj;
}
}
public void show() {
for (int i = 0; i < pos; i++)
System.out.println(data[i]);
}
}
//为了实现等值判断,所以在CharNum类中新增方法equals
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
CharNum charNum = (CharNum) o;
return chars == charNum.chars;
}
}
3、测试类
public class Test5 {
public static void main(String[] args) throws Exception {
Collection col=new Collection();
try (
Reader r = new FileReader("a.txt")
) {
int kk=0;
while((kk=r.read())>-1){
col.add(new CharNum((char)kk));
}
}
col.show();
}
}