2016-12-03 8 views
0

以下のコードは、リストy内の単語がFileReaderまたはリストxを介して文書内に出現した回数を数えます。最終的にはリストyもインポートされた文書にしたいのですが、文書上でコードを実行すると、それは私に誤カウントまたは全くカウントを与えません。どうしたの?マイワードカウントプログラムが動作していません

また、ファイルはメモ帳のフォームです。私は窓を使用しています

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.util.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class test { 
    @SuppressWarnings("resource") 
    public static void main(String[] args) throws Exception { 
     don w = new don(); 

     List<Integer> ist = new ArrayList<Integer>(); 
     // List<String> x =Arrays.asList 
     // ("is","dishonorable","dismal","miserable","horrible","discouraging","distress","anguish","mine","is"); 

     BufferedReader in = new BufferedReader(new FileReader("this one.txt")); 
     String str; 

     List<String> list = new ArrayList<String>(); 
     while ((str = in.readLine()) != null) { 
      list.add(str); 
      // System.out.println(list); 
      List<String> y = Arrays.asList("Hello", "the", "string", "is", "mine"); 
      for (String aY : y) { 
       int count = 0; 
       for (String aX : list) { 
        if (aY.contains(aX)) { 
         count++; 
        } 
       } 
       ist.add(count); 
       // no need to reset the count 
      } 
      int g = ist .stream() 
         .mapToInt(value -> value) 
         .sum(); 
      System.out.println(g); 
     } 
    } 
} 
+2

'don'オブジェクトは何をする予定ですか?それを購入するとインスタンス化し、後でそれを何もしません。私は 'ArrayList'に' count'を格納する理由を理解していません – jpuriol

+0

ドンは関連していないのでこの質問をするときに取り出したいプログラムの一部です。私は数を後で他のことをしたいので、カウントを保存しています。 –

+0

あなたのコードはかなり混乱しますが、問題は、文書のテキスト行と文字列のリストを比較していることです。だから決して一致しません – Safirah

答えて

0

あなたは数えたいと思っています。

ここでは、文字列に部分文字列が含まれているかどうかだけを確認します。あなたの代わりに何をすべき

には、次のおおよそ次のとおりです。

static int count(String line, String word) { 
    int count = 0; 
    for (int offset = line.indexOf(word); offset >= 0; offset = line.indexOf(word, offset + 1 + word.length())) { 
    count++; 
    } 
    return count; 
} 

、もちろん、あなたはおそらく考慮にあなたが部分文字列ではなく言葉を探しているという事実を取らなければなりません。しかし、あなたがすでにそれを習得していれば、正規表現を使ってさらに助けたいかもしれません。

関連する問題