Solution for Quiz II

Problem 1

Consider the following recursive method:
  int slowAdd(int i, int j) {
    System.out.println("i= " + i + ", j= " + j);
    if (i == 0) return j;
    else {
      i = i-1;
      j = j+1;
      return slowAdd(i,j);
    }
  }

Problem 2

Administrators solve any problem by forming a committee. A simple committee consists of some number of people. Given any two committees, it is possible to combine them in a committee of committees. For example, in Java, we would write:
Committee s1 = new SimpleCommittee(4); // creates a committee of 4 people
Committee s2 = new SimpleCommittee(2); // creates a committee of 2 people
Committee s3 = new SimpleCommittee(7); // creates a committee of 7 people
Committee c1 = new CommitteeOfCommittees(s1,s2); 
Committee c2 = new CommitteeOfCommittees(c1,s3); 
Your job is to: You may abbreviate the class names for convenience!

Solution

abstract class Committee {
  abstract int numberOfPeople();
}

class SimpleCommittee extends Committee {
  private int people;
  SimpleCommittee (int p) { people = p; }
  int numberOfPeople() { return people; }
}

class CommitteeOfCommittees extends Committee {
  Committee c1, c2;
  CommitteeOfCommittees (Committee s1, Committee s2) { c1=s1; c2=s2; }
  int numberOfPeople() { return c1.numberOfPeople() + c2.numberOfPeople(); }
}

Problem 3

What is printed by the following program:
class E1 extends Exception {}
class E2 extends Exception {}

class A {
  int m1 () throws E1 {
    System.out.println("Enter m1");
    if (true) throw new E1();
    else {
      System.out.println("Exit m1");
      return 12;
    }
  }

  int m2 () throws E1 {
    System.out.println("Enter m2");
    if (true) throw new E1();
    else {
      System.out.println("Exit m2");
      return 23;
    }
  }

  int m3 () throws E1 {
    System.out.println("Enter m3");
    int x = m1();
    int y = m2();
    System.out.println("Exit m3");
    return x+y;
  }

  int m4 () throws E2 {
    try { 
      System.out.println("Enter m4");
      int result = m3(); 
      System.out.println("Exit m4");
      return result;
    }
    catch (E1 e) { 
      System.out.println("Caught E1");
      throw new E2(); 
    }
  }

  int m5 () {
    try { 
      System.out.println("Enter m5");
      int result = m4(); 
      System.out.println("Exit m5");
      return result;
    }
    catch (E2 e) { 
      System.out.println("Caught E2");
      return 1; 
    }
  }
}

class TestE {
  public static void main (String[] args) {
    A x = new A();
    int result = x.m5();
    System.out.println(result);
  }
}

Solution:

Enter m5
Enter m4
Enter m3
Enter m1
Caught E1
Caught E2
1

Visited times since December 15, 1997 (or the last crash).

sabry@cs.uoregon.edu