15-110 Sections G-J / Spring 2010 / Quiz 2
5 Questions / 30 Minutes
 

·         All code examples compile and run without errors (except where explicitly noted otherwise).
 

1)      Indicate what the following will print:

class Quiz2Trace1 {
  public static void f(int n) {
    n += g(3);
    System.out.println("f:" + n);
  } 

  public static int g(int n) {
    System.out.println("g:" + (n+1));
    return 2*n;
  }

  public static void h() {
    int n = 5;
    f(n+1);
    System.out.println("h:" + n);
    System.out.println("--");
    n = g(5);
    f(n%3);
    System.out.println("h:" + n);
  }

  public static void main(String[] args) {
    h();
  }
}

 

2)      Draw a picture of what the following will paint:

class Quiz2Trace2 extends JComponent {
  public void f(Graphics page, int left, int top, int width, int height) {
    page.drawRect(left, top, width, height);
    g(page, left, top, width, height);
  }

  public void g(Graphics page, int left, int top, int width, int height) {
    int m=width/4;
    page.drawOval(left+m, top, width-2*m, height);
  }

  public void paint(Graphics page) {
    int w = getWidth(), h = getHeight();
    f(page,0,h/2,w,h/4);
    f(page,w/2,h/3,w/4,h/3);
  }
  // gray code goes here...
}

Hint:  2/3 < 3/4, and your picture must reflect this fact!
 

3)      Write a Method
Write a method named
isMultiple that takes two arbitrary (possibly-negative) int values and returns true if the first is a multiple of the second and false otherwise.  Note: multiples of 5 include 10, 5, 0, -5, and -10. Also, the only multiple of 0 is 0 itself.  Your method may not crash in any case.
 

4)      Write a Robotic Test Method
Following our standard pattern (including appropriate print or println statements), write a robotic test method for a method named
hd (short for hundredsDigit) that takes an arbitrary int value and returns the value of its hundreds digit (which is always between 0 and 9, inclusive).  There are at least 3 interesting cases you must test for to receive full credit.  Do not write the hundredsDigit method, just the robotic test method!
 

5)      Write a Graphics Helper Method
Write a graphics helper method named
paintCircle that takes a Graphics page and four values describing a bounding box and fills the largest circle that is centered in the box and does not extend beyond the box.
 

6)      Bonus/Optional:  Indicate what the following will print: (remember: it compiles and runs without errors!)

class Quiz2Bonus {

  public static int f(int x, int y) {

    System.out.println(x + "," + y);

    if (x>y) return f(x-y,y+1); else return x+y;

  }

  public static void main(String[] args) { System.out.println(f(25, f(4,4))); }

}