1. 程式人生 > >檢驗重復字母代碼

檢驗重復字母代碼

集合 ext ava read 沒有 rev ever 臨時 隨著

//信1705-2   20173629   何偉豪
package 論文查重;
import java.io.*;
import java.util.*;

public class 查重 {
    public static void main(String[] args){
        demo(new File("C:\\Users\\Lenovo\\Desktop\\JAVA\\臨時文件\\論文查重\\論文查重\\作文.txt"));
    }
    public static void demo(File file){
        BufferedReader bfr = null
; //定義字符讀取(緩沖)流 try{ bfr = new BufferedReader(new FileReader(file)); String value = null; String newValue = ""; while((value = bfr.readLine())!=null){ //開始讀取文件中的字符 newValue = newValue+value; //存入newValue變量中 }
char[] ch = newValue.toCharArray();//把newValue變成字符數組 TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(Collections.reverseOrder()); for(int x = 0;x<ch.length;x++){ char c = ch[x]; if(tm.containsKey(c)){ //如果TreeMap(tm)中有該鍵,則取出該鍵中的值,也就是出現的次數
int conut = tm.get(c); tm.put(c,conut+1); //存入把新值存入tm集合中,如果鍵相同的話, 新鍵會替換老鍵,值也隨著變化了 } else{ tm.put(c, 1); //如果沒有出現該鍵就說明是第一次出現,然後就存入1次 } } //下面的是取出TreeMap(tm)中的鍵和值 Set<Map.Entry<Character, Integer>> set = tm.entrySet(); Iterator<Map.Entry<Character, Integer>> iter = set.iterator(); while(iter.hasNext()){ Map.Entry<Character, Integer> map = iter.next(); char k = map.getKey(); int v = map.getValue(); System.out.print(k+"("+v+") "); } } catch(IOException e){ System.out.println("文件讀取錯誤"); } finally{ try{ if(bfr!=null) bfr.close(); } catch(IOException e){ System.out.println("文件關閉錯誤"); } } } }

檢驗重復字母代碼