package com.studyjava.chapter5;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Practice6 {
public static void main(String[] args) {
charCounter("D:\\dev\\test\\bw\\copy.txt");
}
public static void charCounter(String filepath) {
FileReader fr = null;
try {
fr = new FileReader(filepath);
int c = -1;
int up = 0;
int low = 0;
while ( (c=fr.read()) != -1) {
if(c==(int)'A')
up++;
if(c==(int)'a')
low++;
}
System.out.println("'A' shows "+up+" times, 'a' shows "+low+" times.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(fr!=null)
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
最后一题
public static void test() {
FileReader reader = null;
try {
reader = new FileReader("demo\\calcCharNum.txt");
StringBuffer str = new StringBuffer();
char[] text = new char[1024];
int length = -1;
int countOfa = 0;
int countOfA = 0;
while ((length = reader.read(text)) > -1) {
str.append(text, 0, length);
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == 'a') {
countOfa++;
} else if (c == 'A') {
countOfA++;
}
}
System.out.println("a出现的次数:" + countOfa + " A出现的次数:" + countOfA);
} catch (IOException e) {
e.printStackTrace();
}
}