Programming Practice: if Statements and Boolean Conditions


SimpleMug class

Constructor

Recall the SimpleMug class constructor (given below). Modify the constructor so that it handles "bad" parameter values.

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

 




fill method

Recall the original fill method:

public void fill(int amount) {
    int newCurrAmount = currAmount + amount;
    currAmount = newCurrAmount;
}

Rewrite the fill method so that it handles overflow: the current amount in the mug should not be allowed to exceed the maximum capacity of the mug and the amount of overflow should be returned.

public int fill(int amount) {

 






Rectangle class

Suppose we have a Rectangle class that begins:

class Rectangle {

    private Point upperLeft;		// the upper left corner point
    private double height;			// the height of the rectangle
    private double width;			// the width of the rectangle

isSquare method

Write an isSquare method that returns true if the rectangle is a square (and false otherwise).



contains method

Write a contains method that returns true if the point passed in is inside the rectangle

public boolean contains(Point p) {

 




Procrastination

An unnamed CS 302 student uses the following (not recommended) rubric to determine whether to procrastinate on a particular assignment:

Suppose that the following variables have been declared and given values:

Write Java code that sets a boolean variable procrastinate to true if the student should decide to procrastinate and false otherwise.

Method 1: use multiple, nested if-elses

Method 2: use only one if-else

Method 3: use no ifs