Interval
Create a class to model intervals of the real line. Each interval has a minimum and a maximum, and contains all of the real numbers between its minimum and its maximum. (This kind of object has applications in geometry, scheduling, and text editing.) For example, the interval [3, 6] from 3 to 6 contains 3, π, 5, and 6, but it does not contain 6.21. (All intervals we deal with will include both endpoints.) Your code must produce the following API:
public Interval(double lo, double hi) // construct interval from lo to hi; but 
                                      // throw a RuntimeException if lo > hi
String toString()                  // return text representation, e.g. "[3, 6]"
boolean contains(double x)         // does this interval contain x?
boolean intersects(Interval other) // do these intervals contain a common point?
boolean subsetOf(Interval other)   // is this interval a subset of the other?
boolean supersetOf(Interval other) // is this interval a superset of the other?
For subsetOf, the containment doesn't have to be strict. For example [3, 4] is a subset of [3, 4.5], and every interval is a subset of itself.
51
 
1
public class Interval {
2
   // instance variables
3
4
5
   // constructor
6
7
8
9
10
11
12
13
14
   // text representation
15
   public String toString() {
16
      // if you want, use String.format("%.6e", ...);
17
18
   }
19
   // other instance methods
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
   // use "this" to just reuse previous logic
37
   public boolean supersetOf(Interval other) {
38
      return other.subsetOf(this);
39
   }
40
   
41
   // test client
42
   public static void main(String[] args) {
43
      // counting years BCE to avoid negative signs
44
      Interval mesozoic = new Interval(66E6, 252E6);
45
      Interval jurassic = new Interval(145E6, 201E6);
46
      StdOut.println("The Mesozoic is " + mesozoic.toString());
47
      StdOut.println("The Jurassic is " + jurassic); // implicit toString
48
      StdOut.println(mesozoic.intersects(jurassic)); // true
49
      StdOut.println(jurassic.subsetOf(mesozoic));   // true
50
   }
51
}