Computer Science 15-110, Spring 2010
Recitation for Week #2

1. Quizlet (quiz #1, part 1)
See quiz1, part 1.

2. Enabling Assertions
Review the "Enabling Assertions" section from the class notes, especially the part on Enabling Assertions in DrJava.

3. CA-Directed Lab
1. "Writing Static Methods" Review
To be sure we cover all of the methods included in the class notes on "Writing Static Methods", in recitation, review the following methods in these notes:
1. square

public static int square(int n) {
return n*n;
}

2. printSquare

public static void printSquare(int x) {
System.out.println(x + "^2 = " + square(x));
}

3. isPositive

public static boolean isPositive(int x) {
return (x > 0);
}

4. areaUnderLine

// This method computes the area in the first quadrant under
// the line y=mx+b.  It assumes m is negative and b is positive,
// so we in fact have a triangle in the first quadrant.
public static int areaUnderLine(int m, int b) {
// The x-intercept of y=mx+b is where y=0, so
// mx+b=0, so x=-b/m
int width = -b/m;
// b is the y-intercept
int height = b;
// now we have the width and height of the right triangle
// under the line in the first quadrant, so...
return width*height/2;
}

5. isEvenPositive

public static boolean isEvenPositive(int x) {
boolean isEven = ((x % 2) == 0);
boolean isPositive = (x > 0);
return (isEven && isPositive);
}

6. minSquared and testMinSquared

class MyCode {
public static int minSquared(int x, int y) {
int min = Math.min(x, y);
return (min * min);
}

public static void testMinSquared() {
System.out.print("Testing minSquared... ");
assert(minSquared(2,3) == 4);
assert(minSquared(3,2) == 4);
System.out.println("Passed all tests!");
}

public static void main(String[] args) {
// remember to enable assertions (with -ea flag)
testMinSquared();
}
}

7. isOdd and testIsOdd

class MyCode {
public static boolean isOdd(int x) {
return ((x % 2) == 1); // ERROR: This contains a bug!
}

public static void testIsOdd() {
System.out.print("Testing isOdd... ");
assert(!isOdd(2));
assert(isOdd(1));
assert(!isOdd(0));
assert(isOdd(-1));  // ERROR: This assertion will fail!
assert(!isOdd(-2));
System.out.println("Passed all tests!");
}

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

4. Student-Directed (Collaborative) Lab
1. triangleArea
Write a method, triangleArea, that takes two integers -- a width and height, both assumed to be non-negative -- and returns the (integer) area of the corresponding triangle.  Include a test method.

2. enoughEggCartons
Write a method, enoughEggCartons, that takes two integers -- the number of eggs and the number of egg cartons, both assumed to be non-negative -- and returns true if there are enough egg cartons to hold that many eggs and false otherwise.  Include a test method.

3. reverseNumber
Write a method, reverseNumber, that takes a 4-digit integer, assumed to be positive, and returns the number in reverse.  So a call to reverseNumber(2468) returns 8642.  Include a test method.