下面的代碼將計算每個字符的出現次數。如果我在文本文件輸出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);
}
}
}
我不會轉換的代碼,而是將它扔了,並重新開始,因爲你會使用不同的邏輯。另外,說實話,你的問題有點泛泛,並沒有顯示你在解決方案上的嘗試,而是一種「這是一些代碼,爲我修復」類型的問題。我建議你先讓自己先行一步,然後如果遇到麻煩,儘自己的最大努力,並提出具體問題,並且可能會得到大量有用的幫助。祝你好運! – 2010-12-06 04:02:37
我已盡力達到我的水平。我的問題是非常基本的問題,因爲我對這個主題很陌生。我沒有要求告訴我整個代碼。我只需要幫助。 – Sumithra 2010-12-06 04:13:22