2017-04-03 4 views
-2

私は上記の質問に答えるために以下のコードを書いています。誰かが私が間違って行ったことを教えてもらえますか?配列の各要素がファイル内で何回出現するかを数えます。

このコードでは、配列の各要素がテキストファイルに含まれる正確な回数が返されることが期待されます。かかわらず、スペース、タブ、改行などの

public class counter { 
    public static void main(String[] args) throws FileNotFoundException { 
     String[] wordname; 
     wordname = new String[] {"harry","ron","george","fred"}; 
     File file = new File("file.txt"); 
     Scanner scanner = new Scanner(file); 
     for(int i=0; i < wordname.length; i++){ 
      scanner.useDelimiter(wordname[i]); 
      int occurences = 0; 
      while(scanner.hasNext()){ 
       scanner.next(); 
       occurences++; 

      } 
      System.out.println(wordname[i] + ": " + occurences); 
     } 
     scanner.close(); 

    } 
} 

出力:
ハリー:6
ロン:1
ジョージ:0
フレッド:0

ファイル:
ハリー・ハリー・ロン・ジョージ・ハリー・ハリー ハリー・ハリー・ハー・
ロン・ロン・ロン・ロンフレッド フレッドフレッド・ジョージ ハリー

+0

あなたの出力は何ですか?あなたは例を挙げることができますか?一度しか通り抜けるようなことはありません。 –

+0

もテキストファイルの内容を表示します。 – sbk

+0

出力: ハリー:6 ロン:1 ジョージ:0 フレッド:0 ファイル: ハリーハリー・ロン・ジョージハリーハリー ハリーハリーHARロンロンロンロン\t \t \tフレッド フレッドフレッド・ジョージ ハリー – codepurveyor

答えて

0

あなたはそれがまたダウンパフォーマンスを作るホワイトスペースの代わりに、言葉とあなたのコードのスキャンファイルの複数の時間を使って分割する必要があります。

だから、このような方法で同じタスクを実行するために良いです:

public class Counter { 
public static void main(String[] args) throws FileNotFoundException { 
    String[] wordname; 
    wordname = new String[]{"harry", "ron", "george", "fred"}; 
    Map<String, Integer> map = new HashMap<>(); 
    for (String string : wordname) { 
     map.put(string, 0); 
    } 
    File file = new File("file.txt"); 
    Scanner scanner = new Scanner(file); 
    scanner.useDelimiter("\\s+"); 
    String word; 
    while (scanner.hasNext()) { 
     word = scanner.next(); 
     if (map.containsKey(word)) { 
      map.put(word, map.get(word) + 1); 
     } 
    } 

    for (Map.Entry<String, Integer> entry : map.entrySet()) { 
     System.out.println(entry.getKey() + ":" + entry.getValue()); 
    } 
} 
} 
0
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Arrays; 
import java.util.Scanner; 

public class Example { 
    public static void main(String[] args) throws FileNotFoundException { 
     //read whole file to string only once 
     String fileContent = new Scanner(new File("file.txt")).useDelimiter("\\Z").next(); 
     String[] wordname = {"harry","ron","george","fred"}; 
     // filter each name and count occurrences 
     for (String name : wordname){ 
      long count = Arrays.stream(fileContent.split(" ")).filter(s -> s.equals(name)).count(); 
      System.out.println(name + " : " + count); 
     } 
    } 
} 
関連する問題