Java

OOP GUIDE / WORK

 

WORDPAIRLIST CLASS SOLUTIONS

 

Topics

  • Advanced class design
  • Aggregation
  • ArrayLists

 

Source

  • This question was part of the 2018 AP exam free response questions.  You can find a link to all free response questions on the previous page.

 

 

TASK – PART 1 – SETUP – WORDPAIR CLASS

 

No solution required.

 

 

TASK – PART 2 – SETUP – STARTER CODE FOR WORDPAIRLIST CLASS

 

No solution required.

 

 

TASK – PART 3 – WORDPAIRLIST CLASS

 

Here is my solution:

 

 

import java.util.ArrayList;

import java.util.Arrays;

 

public class WordPairList

{

     /** The list of word pairs, initialized by the constructor. */

 

     private ArrayList<WordPair> allPairs;

    

     /** Constructs a WordPairList object as described in part (a).

     * Precondition: words.length >= 2

     */

    

     public WordPairList(String[] words)

     {

           allPairs = new ArrayList<WordPair>();

          

           for (int i=0; i<words.length; i++)

           {

                for (int j=i+1; j<words.length; j++)

                {

                      String w1 = words[i];

                      String w2 = words[j];

                      allPairs.add(new WordPair(w1, w2));

                }

           }

     }

 

     /** Returns the number of matches as described in part (b).

     */

 

     public int numMatches()

     {

           int count = 0;

           for (int i=0; i<allPairs.size(); i++)

           {

                WordPair tmp = allPairs.get(i);

                if (tmp.getFirst().equals(tmp.getSecond()))

                {

                      count++;

                }

           }

           return count;

     }

    

     public String toString()

     {

           return allPairs.toString();

     }

}

 

 

TASK – PART 4 – TESTING YOUR CLASS

 

No solution required.