Question

i'm having trouble with a code. I have read words from a text file into a String array, removed the periods and commas. Now i need to check the number of occurrences of each word. I managed to do that as well. However, my output contains all the words in the file, and the occurrences. Like this: the 2 birds 2 are 1 going 2 north 2 north 2

Here is my code:

public static String counter(String[] wordList)
{
    //String[] noRepeatString = null ;
    //int[] countArr = null ;

    for (int i = 0; i < wordList.length; i++) 
    {
         int count = 1;
         for(int j = 0; j < wordList.length; j++)
         {
             if(i != j)  //to avoid comparing itself
             {
                 if (wordList[i].compareTo(wordList[j]) == 0)   
                 {
                     count++;
                     //noRepeatString[i] = wordList[i];
                     //countArr[i] = count;
                 }
             }
         }

         System.out.println (wordList[i] + " " + count);

     }

    return null; 

I need to figure out 1) to get the count value into an array.. 2) to delete the repetitions. As seen in the commenting, i tried to use a countArr[] and a noRepeatString[], in hopes of doing that.. but i had a NullPointerException.

Any thought on this matter will be much appreciated :)

Was it helpful?

Solution

I would first convert the array into a list because they are easier to operate on than arrays.

List<String> list = Arrays.asList(wordsList);

Then you should create a copy of that list (you'll se in a second why):

ArrayList<String> listTwo = new ArrayList<String>(list);

Now you remove all the duplicates in the second list:

HashSet hs = new HashSet();
hs.addAll(listTwo);
listTwo.clear();
listTwo.addAll(hs);

Then you loop through the second list and get the frequency of that word in the first list. But first you should create another arrayList to store the results:

ArrayList<String> results = new ArrayList<String>;
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": " count;
results.add(result);
}

Finally you can output the results list:

for(String freq : results){
System.out.println(freq);}

I have not tested this code (can't do that right now). Please ask if there is a problem or it doesnÄt work. See these questions for reference:

How do I remove repeated elements from ArrayList?

One-liner to count number of occurrences of String in a String[] in Java?

How do I clone a generic List in Java?

OTHER TIPS

some syntax issues in your code but works fine

ArrayList<String> results = new ArrayList<String>();
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": "+ count;
results.add(result);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top