从文本文件中计算出现次数 - 使用映射

3
以下代码将计算每个字符的出现次数。如果文本文件中有abc,则输出将是a 1 b 1 c 1。我在许多网站上读到,for循环将占用大量时间,最好使用哈希映射实现相同的功能。你们中的任何人能帮我把这个程序转换成使用哈希映射的吗?
 import java.io.*;

    class Count_Char {
    public static void main(String[] args) {
        try
        {
    FileInputStream file = new FileInputStream("D:\\trial.txt");
    DataInputStream dis = new DataInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(dis));
    String Contents="";
    String str="";
    while ((Contents = br.readLine()) != null) {
    str+=Contents;
    }
    char[]char_array =str.toCharArray();
    for(int count =0;count<char_array.length;count++){
    char ch= char_array[count];
    int counter=0;
    for ( int i=0; i<char_array.length; i++){
    if (ch==char_array[i])
    counter++;
    }
    boolean flag=false;
    int j=count-1;
    while(j>=0)
        {

        if(ch==char_array[j])
            flag=true;
            j--;
        }
    if(!flag){
    System.out.println(ch+" "+counter);
    }
    }
        }catch(IOException e1){
            System.out.println(e1);
        }
        }
    }

我不会转换那段代码,而是会将其丢弃并重新开始,因为你将使用不同的逻辑。另外,说实话,你的问题有点笼统,并没有展示出你对解决方案的尝试,有点像“这是一些代码,帮我修复一下”的类型问题。我建议你先自己尝试一下,如果遇到困难,再发布你最好的努力,并提出你具体的问题,你很可能会得到很多有帮助的帮助。祝你好运! - Hovercraft Full Of Eels
我已经尽力了。我的问题非常基础,因为我对这个主题非常陌生。我没有要求告诉我整个代码。我只需要帮助。 - Sumithra
我相信你已经尽力了,但我强烈建议你向我们展示你的尝试。否则,我们怎么知道你需要哪些帮助呢? - Hovercraft Full Of Eels
2个回答

2

快速伪代码。基本原理在于将字符作为键保存在Map中,而值是该字符出现次数的计数(键/值对)。

 //declare a map to hold your characters and their counters
 Map<String,Integer> charCounter = new HashMap<String,Integer>();
 //the following if else logic goes when you are looping through your tokens
    if(charCounter.containsKey(<your character>)){
           charCounter.put(<your character>,charCounter.get(<your character>)+1);
    }else{
          charCounter.put(<your character>,1);
    }

完成遍历后,您可以使用以下方法打印地图。
for(String key : charCounter.keySet()) {
            System.out.println(key+" "+charCounter.get(key));
}

0

FileInputStream file = new FileInputStream(""); DataInputStream dis = new DataInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(dis));

文件输入流 file = new FileInputStream(""); 数据输入流 dis = new DataInputStream(file); 缓冲读取器 br = new BufferedReader(new InputStreamReader(dis));

        String temp="";
        Map<String,Integer> charCounter = new HashMap<String,Integer>();
      while ((temp=br.readLine()) != null)
      {
         String[] spliter= temp.split("");
         for(String temp1:spliter)
         if(charCounter.containsKey(temp1)){
               charCounter.put(temp1,charCounter.get(temp1)+1);
        }else{
              charCounter.put(temp1,1);
        }


      }


            System.out.println(charCounter);

基于Logic Coolbean的代码,我已经编写了它...希望这能有所帮助...我已经测试过了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接