CodeWordChecker Solution

The CodeWordChecker problem from the 2018 AP Computer Science A exam was checking that you could create a full class that implemented the following interface.

public interface StringChecker {
    /** Returns true if str is value */
    public boolean isValid(String str);
}

Only one method is defined, which means that the class we’re going to define only has to have an isValid method, although it can contain others. For the CodeWordChecker class that we’re defining a string is considered valid is it’s at least some minimum length but no longer than a maximum, and does not contain a specified string.

We do need to define a couple of constructors as well. There are two example constructor calls in the problem description.

StringChecker sc1 = new CodeWordChecker(5, 8, "$");

and

StringChecker sc2 = new CodeWordChecker("pass");

With these two definitions we need a constructor that takes 2 int parameters followed by a String and another constructor that takes a single String. The two int parameters in the first constructor are the min and max lengths respectively and the String parameter is what cannot be in the String to check. The second constructor only takes a String that cannot be in a valid String to check and should use 6 as the minimum length and 20 as the maximum.

Here is the solution that I came up with.

public class CodeWordChecker implements StringChecker {
    private int min;
    private it max;
    private String no;

    public CodeWordChecker(int min, int max, String no) {
        this.min = min;
        this.max = max;
        this.no = no; 
    }
    public CodeWordChecker(String no) {
        this(6, 20, no);
    }
    public boolean isValid(String str) {
        return str.length() >= min && str.length() <= max && str.indexOf(no) == -1;
    }
}

We needed 3 instance variables. min and max are both int values and hold the minimum and maximum lengths for a value String. no contains the String that cannot be in a valid String.

The two constructors set the instance variable names. I went short and used this in the second constructor to save a little writing.

For the isValid method we look to makre sure that str.length() is within the correct range and that str.indexOf(no) == -1. Were I to write this method for real I probably would have used !str.contains(no) instead, but contains is not part of the AP Java Subset.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.