NumberGroup is #4 from the from the 2015 AP Computer Science A Free Response problems.

Part (a) NumberGroup interface

public interface NumberGroup
    boolean contains(int value);

contains could also be specified as public and/or abstract.

Part (b) Range class

public class Range implements NumberGroup
    private int minValue, maxValue;

    public Range(int minValue, int maxValue)
        this.minValue = minValue;
        this.maxValue = maxValue;

    public boolean contains(int value)
        return minValue <= value && value <= maxValue;

See Class writing order for a technique to respond to AP CS FR that request an entire class.

Part (c) MultipleGroups contains method

public boolean contains(int num)
    for(NumberGroup group : groupList)
            return true;

    return false;

On the free response, when in doubt, use a regular loop (for or while). See Enhanced for loop exercises for information on when enhanced for loops are appropriate, and to practice with them.

2015 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on NumberGroup