8:00 Quiz 4

One-page version suitable for printing.

Statistics:

(including three-point curve)

mean     22.250 (979.000/44)
stddev   6.906
median   23.000
midrange 18.000-28.000

#  avg
1  6.57 / 10
2  6.52 / 10
3  6.16 / 10
 + 3-point curve

Question 4-1

Suppose we add the following method definition to our Bank class.

public class Bank {
    // : (definitions of other methods and variables)

    public void remove(int i) throws NoSuchElementException {
        if(i < 0) {
            throw new NoSuchElementException("negative index");
        } else if(i >= num_accts) {
            throw new NoSuchElementException("index too large");
        } else {
            num_accts--;
            accts[i] = num_accts;
        }
    }
}
Suppose we have a Bank variable named first. How would you use this method to remove the third account from first? Be sure to handle any exceptions that the method might initiate; for full credit, your code display the message associated with the exception (like ``negative index'').
public static void run() {
    Bank first = new Bank();
    // : (code that inserts accounts into the bank)



}

Solution

Question 4-2

Suppose we have the following two class definitions.

class A {
  public int f(int x) {
    return 2 * x;
  }
  public int g(int x) {
    return f(x * 3);
  }
}
class B extends A {
  public int f(int x) {
    return 5 * x;
  }
  public int h(int x) {
    return f(7 * x);
  }
}
And suppose we execute the following run method.
public static void run() {
  B b = new B();
  IO.println(b.f(1) + " " + b.g(1) + " " + b.h(1));
  A a = b;
  IO.println(a.f(1) + " " + a.g(1));
}
What would the method print?

Solution

Question 4-3

Define a class PassCount to track whether all the students of a class have passed a test. It should support the following methods.

PassCount()
(Constructor method) Constructs an object representing an empty class.

void addGrade(double grade)
Adds grade into the class.

boolean isAnyFailing()
Returns true only if there is somebody in the class who received a grade of less than 60.

For example, if you defined this class properly, I should be able to write the following class to test it.
public class PassCountTest {
    public static void run() {
        PassCount a = new PassCount();
        a.addGrade(45.0);
        a.addGrade(76.0);
        IO.println(a.isAnyFailing()); // should print ``true''

        PassCount b = new PassCount();
        b.addGrade(60.0);
        IO.println(b.isAnyFailing()); // should print ``false''
    }
}
Note that, to accomplish this, a PassCount object need not remember every single grade --- that is, you do not need to use arrays: It just needs to remember whether any of the ones it has seen were below 60.

Solution