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); } }
i= 3, j= -1 i= 2, j= 0 i= 1, j= 1 i= 0, j= 2
No. The call slowAdd(-1,3) never gives an answer.
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:
System.out.println(s1.numberOfPeople()); // prints 4 System.out.println(s2.numberOfPeople()); // prints 2 System.out.println(s3.numberOfPeople()); // prints 7 System.out.println(c1.numberOfPeople()); // prints 6 System.out.println(c2.numberOfPeople()); // prints 13
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(); } }
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
sabry@cs.uoregon.edu