import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class StringSum { /** * 統計一段英文中出現次數最多的單詞 * @param filePath 檔案的路徑 * @throws Exception */ public static void stringSumMethod(String filePath) throws Exception{ File file=new File(filePath); FileInputStream input=new FileInputStream(file); BufferedReader bf=new BufferedReader(new InputStreamReader(input)); StringBuffer sb=new StringBuffer(); String content=""; while((content=bf.readLine())!=null){ sb.append(content); } bf.close(); input.close(); //System.out.println(sb.toString()); String[] contents=sb.toString().split(" "); //System.out.println(contents.length); Map<String,Integer> map=new HashMap<String, Integer>(); for(int i=0;i<contents.length;i++){ //System.out.println(contents[i]); if(contents[i].equals("0")) continue; int times=1; for(int j=0;j<contents.length;j++){ if(contents[j].equals("0")) continue; if(i==j) continue; if(contents[i].equals(contents[j])){ times++; contents[j]="0";//出現重複的就將重複的字元置"0" } //System.out.println(contents[i]+":"+times+"當前次數:"+j); } //System.out.println(contents[i]+":"+times+"當前次數:"+i); map.put(contents[i],times); } // System.out.println(map.size()); //System.out.println(map.toString()); int maxValue=0; String maxKey=""; for (Map.Entry<String, Integer> entry : map.entrySet()) { // System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); if(entry.getValue()>maxValue){ maxValue=entry.getValue(); maxKey=entry.getKey(); } } System.out.println("出現最多的字串:"+maxKey+" 出現次數:"+maxValue); } }