简体   繁体   中英

My word count program is not working

The code below is meant to count the number of times the words in list y occur either in a document via FileReader or list x. Eventually I want list y to be an imported document as well, but when I run the code on a document it either gives me a false count or no count at all. What's going on?

Also the files are form notepad. I'm using 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);
        }
    }
}

If you want to count, you should... count.

Here, you only check if the string contains a substring.

What you should do instead is roughly the following:

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;
}

Now, of course, you probably have to take into account the fact that you're looking for substrings and not words. But then if you already learned that, you might want to use regular expressions to help you further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM