2016-03-23 2 views
-2

txtファイル内の同じ文字列の出現回数をカウントする必要があります。LinkedHashMapを使用した出現回数のカウント

私は何が出ていること

public class CountWords { 
public File file; 
public Scanner scan = null; 
public LinkedHashMap<String, Integer> list = new LinkedHashMap<>(); 

public CountWords(String txt) { 
    file = new File(txt); 
} 

public void textEdit() { 

    try { 
     scan = new Scanner(file); 
    } catch (FileNotFoundException e) { 
     System.out.println("----"); 
    } 

    while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     if(!list.containsKey(line)) 
      list.put(scan.next(),1); 
     else { 
      list.put(line,list.get(line)+1); 
     } 
    } 
    scan.close(); 
} 
public List<String> getResult(){ 
    textEdit(); 
    return list; 
} 

主が何らかの方法で変更すべきではないクラス(つまり、要件です) で、出力が理由です(入力と同じ順序でなければなりませんLinkedHashMapが使用されています)

public class Main { 
    public static void main(String[] args) throws Exception { 
     String fname = System.getProperty("user.home") + "/textforwords.txt"; 
     CountWords cw = new CountWords(fname); 
     List<String> result = cw.getResult(); 
     for (String wordRes : result) { 
      System.out.println(wordRes); 
     } 
    } 
} 

私は分かりません。

+0

これはコンパイルできますか? getResultはListを返すよう宣言されていますが、LinkedHashMapを返しています。 – JimmyJames

+0

@JimmyJamesいいえ これは私が混乱しているところです "Mainを変更しない"と "LinkedHashMapを使用しない"という要求があったので、何とかこの2つのものを接続する必要があります – Yun8483

+0

リストはどのような文字列を返すべきですか? getResult() 'が含まれていますか?この仕様がありますか? – vanje

答えて

2

文字列または行数が必要ですか?

あなたは、文字列のカウント、このしようとする必要がある場合:

while (scan.hasNext()) { 
    String line = scan.next(); 
    if(!list.containsKey(line)) 
     list.put(line,1); 
    else { 
     list.put(line,list.get(line)+1); 
    } 
} 

をそしてgetResultあなたは次のように変更することができます。

public List<String> getResult(){ 
    textEdit(); 

    ArrayList<String> result = new ArrayList<>(); 
    for(Map.Entry<String, Integer> entry : list.entrySet()){ 
     result.add(entry.getKey() + " " + entry.getValue()); 
    } 
    return result; 
} 

P.S.コメントを追加できません

+0

完璧!どうもありがとう! – Yun8483

関連する問題