2017-04-03 95 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
fred的:0

文件:
harry harry ron george harry harry harry harry har
羅恩·羅恩·羅恩·羅恩·弗雷德 弗雷德弗雷德·喬治 哈利

+0

你是什麼輸出?你能給個例子嗎?似乎它可能只會經歷一次。 –

+0

也顯示文本文件中的內容。 – sbk

+0

輸出: 哈里:6 羅恩:1 喬治:0 fred的:0 文件: 哈里哈里潤·喬治哈里哈里 哈里哈里HAR羅恩羅恩羅恩羅恩\t \t \t fred的 fred的fred的喬治 哈里 – 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); 
     } 
    } 
} 
相關問題