Question 0-5

At right, write a definition of a new type, called IntRange, representing a range of integers. This class should support the following instance methods.

IntRange(int start, int end)
(Constructor method) Sets up a new IntRange object representing the set of integers between start and end, including these two endpoints. The method may assume that the first parameter is below or equal to the second parameter.
int getSize()
Returns the number of integers in the range.
boolean contains(int i)
Returns true if i lies within the range.
The following example method, which uses the IntRange class you define, illustrates how the class should work.
public static void run() {
    IntRange range = new IntRange(2, 4);
    IO.println(range.getSize());         // this prints ``3''
    IO.println(range.contains(1));       // this prints ``false''
    IO.println(range.contains(3));       // this prints ``true''
    IO.println(range.contains(4));       // this prints ``true''
    IO.println(range.contains(5));       // this prints ``false''
}
public class IntRange {



}

Solution

public class IntRange {
    private int first;
    private int last;

    public IntRange(int start, int end) {
        first = start;
        last = end;
    }

    public int getSize() {
        return last - first + 1;
    }

    public boolean contains(int i) {
        return start <= i && i <= last;
    }
}

Back to Midterm 0