Solutions for
Programming Practice: if Statements and Boolean Conditions


SimpleMug class

Constructor

public SimpleMug(int maxCapacity, String liquidKind) {
    if (maxCapacity < 0)
        MAX_CAPACITY = 0;
    else
        MAX_CAPACITY = maxCapacity;
    this.currAmount = 0;
    this.liquidKind = liquidKind;
    if (this.liquidKind == null)
        this.liquidKind = "";
    SimpleMug.mugCounter++;
}

Here's another solution that uses the selection (conditional) operator:

public SimpleMug(int maxCapacity, String liquidKind) {
    MAX_CAPACITY = (maxCapacity < 0) ? 0 : maxCapacity;
    currAmount = 0;
    this.liquidKind = (liquidKind == null) ? "" : liquidKind;
    SimpleMug.mugCounter++;
}

fill method

public int fill(int amount) {
    int newCurr = currAmount + amount;
    int overflow;
    if (newCurr > maxCapacity) {
        currAmount = maxCapacity;
        overflow = newCurr - maxCapacity;
    } else {
        currAmount = newCurr;
        overflow = 0;
    }
    return overflow;
}

Rectangle class

isSquare method

There are many ways to write this. Here's an answer that is commonly given (but less than ideal -- see below):

public boolean isSquare() {
    return height == width;
}

Here's a way that is more complicated but preferable because the dimensions of the square are doubles. It tests that height and width are "sufficiently close" to each other.

public boolean isSquare() {
    final double EPSILON = 0.0000000000001;
    return Math.abs(height - width) < EPSILON;
}

contains method

public boolean contains(Point p) {
    int x_ul = upperLeft.getX(), y_ul = upperLeft.getY(),
        x_p = p.getX(), y_p = p.getY();     // having shorter names will be useful
    
    if ( (x_ul < x_p && x_p < x_ul + width) &&
         (y_ul - height < y_p && y_p < y_ul) )
        return true;
    else
        return false;
        
   // or, even better, discard the if-else and just return the
   // value calculated in the boolean expression, i.e.,
   //
   //   return (x_ul < x_p && x_p < x_ul + width) &&
   //          (y_ul - height < y_p && y_p < y_ul)
}

Procrastination

Method 1: use multiple, nested if-elses

if (days < 2)
    procrastinate = false;
else if (days > 5)
    procrastinate = true;
else // 2 <= days <= 5
    if (temp > 70)
        procrastinate = true;
    else if (temp > 55 && !isRaining)
        procrastinate = true;
    else
        procrastinate = false;

Method 2: use only one if-else

if ( (days > 5) ||
     ( days >=2 && ( temp > 70 || (temp >55 && !isRaining) ) ) )
    procrastinate = true;
else
    procrastinate = false;

Method 3: use no ifs

procrastinate =  (days > 5) || ( days >=2 && ( temp > 70 || (temp >55 && !isRaining) ) );