views:

76

answers:

2

I'm trying to write a method named isLowerThanFreezing that returns true if the Temperature object represents a temperature below the freezing point for water (32.0 F, 0.0 C, or 273.15 K), and false otherwise. This method should include only one inequality (i.e, one comparison formed using <, <=, >, or >=), which can be accomplished by determining the value of the temperature in one of the three scales before performing the necessary comparison with the freezing point for that scale. I already have a method that does the necessary conversion but i'm not entirely sure how to structure the whole method in general

Any help is greatly appreciated!! Thanks

public boolean isLowerThanFreezing(double value, char scale) {

    if (Temperature <= (0.0) 'C') {
    convertTo();
    return true;
    } else {
    return false;
    }
}

convertTo is the method i have for the conversions

+1  A: 

return this.toCelsius() < 0.0;

Nikita Prokopov
Don't do people's homework for them.
Jonathan Feinberg
Although this sounds like homework, it's still a nice topic to discuss about object encapsulation.
Ravi Wallau
+1  A: 

I think I would implement the interface Comparable in the class Temperature, and the implementation of this interface:

class Temperature implements Comparable<Temperature> {
    private double kelvinTemperature; // Kelvin is probably the better scale to store a temperature 
    public int compareTo(Temperature t) {
        if(t.kelvinTemperature > this.kelvinTemperature)
            return 1;
        else if (t.kelvinTemperature < this.kelvinTemperature)
            return -1;
        else
            return 0; 
    }
}

I would also add some static factory methods, such as:

public static Temperature fromCelsius(double celsiusTemperature)

And I Would create some constants for known temperatures, such as the water freezing point:

public static Temperature WATER_FREEZING_POINT = Temperature.fromCelsius(0.0);

And then it would all be a matter of comparing then both:

boolean belowFreezing = temperatureInstance.compareTo(WATER_FREEZING_POINT) < 0;

Perhaps you should use just an integer to represent the temperature if you don't need the extra precision. You're not dealing with money, so double should be enough, but if it isn't, then perhaps BigDecimal is more suitable.

This implementation completely encapsulates your code from numeric comparisons and it also doesn't bloat the implementation with methods like "isBelowFreezingPoint()"

Ravi Wallau