/* An instance of this class represents a temperature (reading). ** It supports both Celsius and Fahrenheit scales. */ public class Temperature { // class constants // --------------- public final int CEL_MODE = 0; // Celsius mode public final int FAH_MODE = 1; // Fahrenheit mode //RWM: using boolean values would be better (assuming that there would // never be reason to expand the set of modes to more than two). // instance variables // ------------------ private int mode; // value is either CEL_MODE or FAH_MODE private double degrees; // on scale corresponding to current mode // constructor // ----------- /* Initializes this Temperature to be in the specified mode and to ** have the specified value in degrees on the corresponding scale. ** If initMode is equal to neither CEL_MODE nor FAH_MODE, an ** IllegalArgumentException is thrown. */ public Temperature(double initDegrees, int initMode) { if (initMode == CEL_MODE || initMode == FAH_MODE) { this.mode = initMode; this.degrees = initDegrees; } else { throw new IllegalArgumentException("initMode value invalid"); } } //RWM: Had the mode been of type boolean, it would be impossible for // the client to pass an "invalid" value via the second parameter. // observers // --------- /* Reports whether or not this temperature is in Celsius mode. */ public boolean inCelsiusMode() { return mode == CEL_MODE; } /* Returns this temperature's value/reading on the scale corresponding ** to its current mode. */ public double getDegrees() { return this.degrees; } // mutators // -------- /* Sets this temperature to the specified number of degrees, ** interpreted to be a measure on the scale corresponding to ** the current mode. */ public void setToDegrees(double numDegrees) { this.degrees = numDegrees; } /* Changes this temperature by the specified # of degrees. ** The parameter's value is interpreted to be a # of degrees on the ** scale corresponding to this temperature's current mode. */ public void change(double delta) { this.setToDegrees(this.degrees + delta); } /* Sets this temperature to Fahrenheit mode. */ public void setToFahMode() { if (this.inCelsiusMode()) { this.mode = FAH_MODE; this.degrees = celToFah(this.degrees); } } /* Sets this temperature to Celsius mode. */ public void setToCelMode() { if (!this.inCelsiusMode()) { this.mode = CEL_MODE; this.degrees = fahToCel(this.degrees); } } // utility methods // --------------- /* Given a temperature reading on the Celsius scale, returns the ** corresponding temperature reading on the Fahrenheit scale. */ private double celToFah(double deg) { return (9.0 / 5.0) * deg + 32.0; } /* Given a temperature reading on the Fahrenheit scale, returns ** the corresponding temperature reading on the Celsius scale. */ private double fahToCel(double deg) { return (deg - 32.0) * (5.0 / 9.0); } }