永发信息网

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

答案:2  悬赏:10  手机版
解决时间 2021-01-14 02:08
  • 提问者网友:呐年旧曙光
  • 2021-01-13 16:17
用JAVA编写一个程序,统计一个文本文件中字符A的个数
最佳答案
  • 五星知识达人网友:平生事
  • 2021-01-13 17:18
注意我的文件路径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);
    }
}
全部回答
  • 1楼网友:醉吻情书
  • 2021-01-13 18:11

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:代码对于题中文件和查找字符已经单独封装成一个方法,可以灵活改动所需要查找的文件和查找的字符。
追问谢谢
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯