Object-Oriented Programming with Java, part I – Exercise 87

This exercise involves creating methods to compare apartments with other apartments to find the price difference, etc…

My Code

Main


public class Apartment {

    private int rooms;
    private int squareMeters;
    private int pricePerSquareMeter;

    public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {
        this.rooms = rooms;
        this.squareMeters = squareMeters;
        this.pricePerSquareMeter = pricePerSquareMeter;
    }

    public boolean larger(Apartment otherApartment) {
        if (this.squareMeters > otherApartment.squareMeters) {
            return true;
        }
        return false;

    }

    public int priceDifference(Apartment otherApartment) {
        int price1 = this.pricePerSquareMeter * this.squareMeters;
        int price2 = otherApartment.pricePerSquareMeter * otherApartment.squareMeters;
        int value = price1 - price2;
        return Math.abs(value);
    }

    public boolean moreExpensiveThan(Apartment otherApartment) {
        int price1 = this.pricePerSquareMeter * this.squareMeters;
        int price2 = otherApartment.pricePerSquareMeter * otherApartment.squareMeters;
        if (price1 > price2) {
            return true;
        }
        return false;
    }
}

Model Code

public class Apartment {

 

    private int rooms;

    private int squareMeters;

    private int pricePerSquareMeter;

 

    public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {

        this.rooms = rooms;

        this.squareMeters = squareMeters;

        this.pricePerSquareMeter = pricePerSquareMeter;

    }

    

    public boolean larger(Apartment compared){

        return this.squareMeters>compared.squareMeters;

    }

    

    private int price(){

        return pricePerSquareMeter*squareMeters;

    }

    

    public int priceDifference(Apartment compared) {

        // Math.abs returns the absolute value

        return Math.abs(this.price()-compared.price());

    }

    

    public boolean moreExpensiveThan(Apartment compared){

        return this.price()>compared.price();

    }    

}

 

Comments

Sometimes you just don’t want to post an exercise. For instance, in the one above I have completely forgotten that it a statement evaluates to boolean true. So although my code works it involves four extra variables and three redundant if statements. Arghhhh.

Leave a comment