永发信息网

用JAVA编写一个程序,统计一个文本文件中字符A的个数

答案:2  悬赏:10  手机版
解决时间 2021-01-14 02:08
用JAVA编写一个程序,统计一个文本文件中字符A的个数
最佳答案
注意我的文件路径url。改成自己的实际路径
另外我的类名叫Demo,你也可以改成自己的
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Demo
{
    public static void main(String[] args)
    {
        
        String url = "D:/Test.txt";
        
        File file = new File(url);
        if (!file.exists() || file.isDirectory())
        {
            System.out.println("文件不存在!");
            return;
        }
        StringBuffer sb = null;
        BufferedReader br;
        try
        {
            br = new BufferedReader(new FileReader(file));
            String temp = null;
            sb = new StringBuffer();
            temp = br.readLine();
            while (temp != null)
            {
                sb.append(temp + "");
                temp = br.readLine();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        String info = sb.toString();
        int num = 0;
        for (int i = 0; i < info.length(); i++)
        {
            
            if ("A".equals(info.charAt(i) + ""))
            {
                num++;
            }
        }
        System.out.println("文件中A的个数:" + num);
    }
}
全部回答

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
System.out.println("Please input the path of the file:");
Scanner scanner = new Scanner(System.in);
String path = scanner.nextLine();
scanner.close();
File file = new File(path);
char des = 'A';
int count = process(file, des);
System.out.println("字符" + des + "在文中出现的次数为:" + count);
}
public static int process(File file, char c) {
int count = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String temp = "";
while ((temp = br.readLine()) != null) {
char[] des = temp.trim().toCharArray();
for (int i = 0; i < des.length; i++) {
if (des[i] == c){
count++;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
}
测试文件:

运行截图:


PS:代码对于题中文件和查找字符已经单独封装成一个方法,可以灵活改动所需要查找的文件和查找的字符。
追问谢谢
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
江淮国四6米8冷藏车载重多少吨
想瘦脸,有什么好方法吗
硕士研究生去沈阳自动化所工作怎么样?
你好 最新款xps15一插入耳机就没声音 拔掉以
黄岛社保中心几点上班
W-inds粉进来拉~~跪求一首歌曲名字~
盐都是显中性的吗?
恋伊升降衣架地址有知道的么?有点事想过去
求问泥地无法造建筑和地板该怎么办
定阻功放是什么意思
徐梓涵楷书字体怎么写
天水市的自然地理要素差异
—Have you joined in a dragon boat race?
汽车尾部标的油耗7.1L是什么意思
2018年1月20号2点左右生的孩子缺啥命里缺啥
推荐资讯
魅族手机怎样从 sim卡联系人
“一隅”是什么意思?
甲午战争中吉野号的历史
寻找70,80年代的电视连续剧(提供名字就好了
DOI10.1007/s11042-013-1610-x什么意思
如图是中东石油外运航线,以下说法正确的是A.
美合商业街地址在什么地方,想过去办事,
蚌埠有没有招商银行
美国的明尼苏达州和中国的时差是多少?比如中
国家对离休干部居住面积的规定是什么?
埃及这个文化古国为什么这么多人?
DNF现在GF和HF还差多少内容?
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?