SE450: Midterm Practice: Filters [4/28] Previous pageContentsNext page

For questions see the homework.

file:functions/two/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package functions.two;
interface Stream {
  int next();
}

class IntStream implements Stream {
  private int i = -1;
  public int next() {
    return ++i;
  }
}

interface Predicate{
  boolean evaluate(int j);
}

class FilteredStream implements Stream{
  private Stream it;
  private Predicate p;

  public FilteredStream(Stream it, Predicate p) {
    this.it = it;
    this.p =p;
  }

  public int next() {
    int i;
    do {
      i = it.next();
    } while (!p.evaluate(i));
    return i;
  }
}

class IsEven implements Predicate {
  public boolean evaluate(int j){
    return (j%2)== 0;
  }
}
class Main {
  public static void main (String[] args) {
    IntStream I = new IntStream();
    FilteredStream F = new FilteredStream(I, new IsEven());
    System.out.println(F.next());   // prints 0 on the screen
    System.out.println(F.next());   // prints 2 on the screen
    System.out.println(F.next());   // prints 4 on the screen
    System.out.println(F.next());   // prints 6 on the screen
    System.out.println(F.next());   // prints 8 on the screen

    IntStream J = new IntStream();
    J.next();                       // move forward one item in J
    FilteredStream G = new FilteredStream(J, new IsEven());
    System.out.println(G.next());   // prints 2 on the screen
    System.out.println(G.next());   // prints 4 on the screen
    System.out.println(G.next());   // prints 6 on the screen
    System.out.println(G.next());   // prints 8 on the screen

    IntStream K = new IntStream();
    class Div3 implements Predicate {
      public boolean evaluate(int n) { return (n%3) == 0; }
    }
    FilteredStream H = new FilteredStream(K, new Div3());
    System.out.println(H.next());   // prints 0 on the screen
    System.out.println(H.next());   // prints 3 on the screen
    System.out.println(H.next());   // prints 6 on the screen
    System.out.println(H.next());   // prints 9 on the screen
  }
}

Previous pageContentsNext page