The final free response question on the 2015 AP Computer Science exam had you working with classes and interfaces. My guess is that if you understand how interfaces work, this was probably the easiest FRQ from 2015 because there really wasn’t much logic to it.
For part A you are writing an interface named NumberGroup
with a single contains
method. contains
should take a single int
parameter and return true
if that value is in a group of numbers.
public interface NumberGroup {
public boolean contains(int n);
}
My guess is what they were looking for is that you know how to create an interface and how to put a method into it because there really wasn’t much to it.
Part B has you implement the NumberGroup
interface you just created into a class called NumberGroup
.
NumberGroup
needs a constructor that takes two values and the contains
method from NumberGroup
.
This is what I came up with, and I think it’s probably the simplest solution. The constructor stores the passed minimum and maximum values in instance variables. contains
then compares nto those two values to see if it’s in range.
public class Range implements NumberGroup {
private int min;
private int max;
public Range(int min, int max) {
this.min = min;
this.max = max;
}
public boolean contains(int n) {
return n >= min && n <= max;
}
}
This isn’t the only solution, of course. As long as your logic worked, it was a good solution. My personal favorite was a student that used an ArrayList
as the instance variable, stored every value from minto
maxin
the constructor, and then iterated through the list in contains
to see if it had that value.
Had this come up in class I probably would have shown it during a code review. It works and is different than most students would have come up with.
import java.util.*;
public class Range implements NumberGroup {
private List<Integer> nums;
public Range(int min, int max) {
nums = new ArrayList<>();
for (int i=min; i<=max; i++) {
nums.add(i);
}
}
public boolean contains(int n) {
for (int i=0; i<nums.size(); i++) {
if (nums.get(i) == n) {
return true;
}
}
return false;
}
}
For the last part you had to go through a list of NumberGroup
references and check if any of them contained a specific value. You’re writing a contains
method that’s going to call other contains
methods.
You’re told that the class you’re working in has the following instance variable defined.
private List<NumberGroup> groupList;
Since it’s a list of NumberGroup
references you know that they’ll all have a contains
method. So we’ll just call that method for each member. If we find one where contains
returns true
then we should return true
. If we get all the way through without finding a match, we return false
.
public boolean contains( int num ) {
for (NumberGroup ng: groupList) {
if (ng.contains(num)) {
return true;
}
}
return false;
}