-1

I am trying to print elements of an arraylist which stores objects. Simply I want the method wordIndexer to print out how many times the word that is given is seen in the title of the object. In this example I am trying to print "we" there is 3 occurrences of "we", but unfortunately I can only print it once.

public class RedditThingIndexer {

    static List<String> words = new ArrayList<>();

    public static String wordIndexer(List<RedditThing> list, String word) {
        int count = 0;
        for (RedditThing thing : list) {
            if (thing.getTitle().toLowerCase().contains(word.toLowerCase())) {
                count++;
                words.add(word);
            }
        }
        return word + " appears: " + count + "\n"
                + "New list: " + words;
    }
}

This is my method call:

System.out.println(RedditThingIndexer.wordIndexer(list, "we"));

And here is the text provided that I am trying to extract from:

[85kaz5 Why do we use pillows now when we sleep? Did we need this during the prehistoric/ancient age? What changed?  askscience 18563 1521502020 ]

1 Answers1

2
public static void wordIndexer() {

    String text = "85kaz5 Why do we use pillows now when we sleep? Did we need this during the prehistoric/ancient age? What changed?  askscience 18563 1521502020";
    String[] words = text.split(" ");
    String wordToMatch = "we";
    int count = 0;
    for (int i=0;i<words.length;i++) {
      if (words[i].toLowerCase().contains(wordToMatch.toLowerCase())) {
        count++;
      }
    }
  }

You can try this solution.

thedarkpassenger
  • 7,158
  • 3
  • 37
  • 61
  • It works, but unfortunately not in my situation.. I might be doing something wrong. I'll keep looking at it, thanks for your help – Sombra Devon Apr 17 '18 at 05:19