[英]My word count program is not working
下面的代碼用於計算列表y中的單詞通過FileReader
或列表x在文檔中出現的次數。 最終,我也希望列表y也成為導入的文檔,但是當我在文檔上運行代碼時,它要么給我一個錯誤的計數,要么根本不給我計數。 這是怎么回事?
這些文件也是表單記事本。 我正在使用Windows
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);
}
}
}
如果您想數數,您應該...數數。
在這里,您僅檢查字符串是否包含子字符串。
相反,您應該大致執行以下操作:
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;
}
現在,當然,您可能必須考慮到要查找子字符串而不是單詞的事實。 但是,如果您已經了解了這一點,則可能需要使用正則表達式來進一步幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.