# Number Group Solution

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.

### Part A

For part A you are writing an interface named NumberGroupwith a single containsmethod. containsshould take a single intparameter and return trueif 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

Part B has you implement the NumberGroupinterface 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. containsthen 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 containsto 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++) {
}
}

public boolean contains(int n) {
for (int i=0; i<nums.size(); i++) {
if (nums.get(i) == n) {
return true;
}
}
return false;
}
}

### Part C

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 containsmethod 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;
}