Home 2015 FRQ 4
Post
Cancel

2015 FRQ 4

  1. This question involves the design of an interface, writing a class that implements the interface, and writing a method that uses the interface.

(a) Write an interface named NumberGroup that represents a group of integers. The interface should have a single contains method that determines if a given integer is in the group. For example, if group1 is of type NumberGroup, and it contains only the two numbers -5 and 3, then group1.contains(-5) would return true, and group1.contains(2) would return false. Write the complete NumberGroup interface. It must have exactly one method

1
2
3
4
//The interface keyword is used to declare a special type of class that only contains abstract methods.
public interface NumberGroup {
    boolean contains(int num);
}

(b)Write the Range class, which is a NumberGroup. The Range class represents the group of int values that range from a given minimum value up through a given maximum value, inclusive. Include all necessary instance variables and methods as well as a constructor that takes two int parameters. The first parameter represents the minimum value, and the second parameter represents the maximum value of the range. You may assume that the minimum is less than or equal to the maximum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//have never seen "implements" before. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends).

public class Range implements NumberGroup {
    //private instances
    private int min;
    private int max;

    //constructor
    public Range(int min, int max){
        this.min=min;
        this.max=max;
    } 

    //had to add this part after checking the solution. I guess I didn't see how i needed it from the question alone??
    public boolean contains(int num){
        return num >= min && num <= max;
    } 
}

(c)Write the MultipleGroups method contains. The method takes an integer and returns true if and only if the integer is contained in one or more of the number groups in groupList.

1
2
3
4
5
6
7
8
9
public boolean contains(int num){
    //for each loop 
    for (NumberGroup group : groupList){
        if (group.contains(num)){
            return true;
        }
    }
    return false;
}
This post is licensed under CC BY 4.0 by the author.

2015 FRQ 3

Individual Seed Blog