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.
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 if 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.
We needed 3 instance variables. min
and max
are both int
values and hold the minimum and maximum lengths for a valid String
. no
contains the String
that cannot be in a valid String
.
The two constructors set the instance variable values. I went short and used this
in the second constructor to save a little writing.
For the isValid
method we look to make 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.
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?