2010-12-06 31 views
3

下面的代碼將計算每個字符的出現次數。如果我在文本文件輸出abc會是1 b 1 c 1.我在許多站點閱讀循環將花費大量的時間,最好是使用哈希映射實現相同。你可以幫助我如何轉換這個程序實現哈希映射?從使用文本文件的地圖中計算出現次數

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); 
     } 
     } 
    } 
+0

我不會轉換的代碼,而是將它扔了,並重新開始,因爲你會使用不同的邏輯。另外,說實話,你的問題有點泛泛,並沒有顯示你在解決方案上的嘗試,而是一種「這是一些代碼,爲我修復」類型的問題。我建議你先讓自己先行一步,然後如果遇到麻煩,儘自己的最大努力,並提出具體問題,並且可能會得到大量有用的幫助。祝你好運! – 2010-12-06 04:02:37

+0

我已盡力達到我的水平。我的問題是非常基本的問題,因爲我對這個主題很陌生。我沒有要求告訴我整個代碼。我只需要幫助。 – Sumithra 2010-12-06 04:13:22

回答

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));

 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); 

建立在邏輯coolbean HAV給writtn它..Hope這將有助於...我已經測試了這個..

相關問題