Search code examples
javaapitwitterlogiceclipse-photon

Twitter API with a Logic applied to it


I am a beginner in Java programming and I have an assignment where I need to get posts from the Twitter API and implement a logic using Eclipse Java Photon.

I managed to get the Twitter posts using Twitter 4j API but I am stuck of how to calculate the average words per tweet for the last 5 tweets.

Can anyone help me understand how to do this please ?


Solution

  • You can get tweet contents and then split them into words. After that you can get average word count by counting the words and dividing it to tweet count.

    This code may help you to achieve that logic:

    
    public class Solution {
        public static void main(String args[]) {
            Solution.printAverageWordCount();
        }
    
        public static void printAverageWordCount(){
            Query query = new Query("");
            query.setCount(100);
            query.setResultType(Query.RECENT);
    
            int statusLimit = 5;
            int wordCount = 0;
            int tweetCount;
    
            do {
                QueryResult result = twitter.search(query);
                statuses = result.getTweets();
                System.out.prinln("Fetch " + statuses.size() + " statuses. Completed in: " + result.getCompletedIn());
    
                tweetCount = 0;
    
                for (Status status : statuses) {
                    wordCount += status.getText().split("\\s+").length;
                    tweetCount++;
                    if(tweetCount >= statusLimit) {
                        break;
                    }
                }
    
                query = result.nextQuery();
            } while (tweetCount < statusLimit);
    
    
            // calculate average
    
            double average = wordCount/(double)tweetCount;
            System.out.println(average);
        }
    
    }