A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© _J2EE_LiXiZhen 中级黑马   /  2017-11-19 23:02  /  1083 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在C盘下有一个文本文件test.txt(里面的内容由数字和字母组成)
定义一个方法统计test.txt文件中指定字符出现的次数。
比如a字符在文件中出现了10次则调用方法传入a后,方法内部输出:a出现10次

[mw_shl_code=java,true]public class Test02 {
        public static void main(String[] args) throws IOException {
                File file = new File("stu.txt");
                int count = getNum(file, 'a');
                System.out.println("'a'出现了" + count + "次");
        }

        public static int getNum(File file, char a) throws IOException {
                int count = 0;
                FileInputStream fis = new FileInputStream(file);

                int len;
                while ((len = fis.read()) != -1) {
                        if (a == (char) len) {
                                count++;
                        }
                }
                return count;
        }
}[/mw_shl_code]

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马