Java

OOP GUIDE / WORK

 

WORDMATCH CLASS SOLUTIONS

 

Topics

  • Method implementation
  • Finding number of occurrences of a string in another string
  • Comparing two strings alphabetically (using compareTo)

 

Source

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

 

 

TASK – PART 1 – SETUP – WORDMATCH CLASS STARTER CODE

 

No solution required.

 

TASK – PART 2 – WORK

 

Here is my solution:

 

 

public class WordMatch

{

     /** The secret string. */

     private String secret;

    

    

     /** Constructs a WordMatch object with the given secret string of lowercase letters. */

 

     public WordMatch(String word)

     {

           secret = word;

     }

    

    

     /** Returns a score for guess, as described in part (a).

      * Precondition: 0 < guess.length() <= secret.length()

      */

    

     public int scoreGuess(String guess)

     {

           //Calculate occurrences of guess in secret.

           int index = secret.indexOf(guess);

           int occ = 0;

           while (index != -1)

           {

                occ++;

                index = secret.indexOf(guess, index+1);

           }

          

           //Calculate and return score.

           int score = occ * guess.length() * guess.length();

           return score;

     }

    

    

     /** Returns the better of two guesses, as determined by scoreGuess and the rules for a

      * tie-breaker that are described in part (b).

      * Precondition: guess1 and guess2 contain all lowercase letters.

      * guess1 is not the same as guess2.

      */

    

     public String findBetterGuess(String guess1, String guess2)

     {

           int score1 = scoreGuess(guess1);

           int score2 = scoreGuess(guess2);

           if (score1 > score2)

                return guess1;

           else if (score2 > score1)

                return guess2;

           else //if score1 == score2

           {

                if (guess1.compareTo(guess2) > 0)

                      return guess1;

                else if (guess1.compareTo(guess2) < 0)

                      return guess2;

                else //same word (should not happen)

                      return guess1; 

           }

     }

}

 

 

 

 

TASK – PART 3 – TESTING YOUR CLASS

 

No solution required.