/* * Temperature.java * * Computer Science 112, Boston University * * Temperature class representing a temperature value with a scale (Celsius or Fahrenheit) */ class Temperature { // Fields to store temperature value and scale private double temperature; private String scale; /* * Constructor to initialize temperature and scale * We make them private to prevent direct access from outside the class. */ public Temperature(double temperature, String scale) { this.setScale(scale); this.setTemperature(temperature); } /* * An accessor method method to retrieve the temperature value */ public double getTemperature() { return temperature; } /* * Setter method to set the temperature value */ public void setTemperature(double temperature) { if (this.getScale().equals("celsius") && temperature > -273.15 || this.getScale().equals("fahrenheit") && temperature > -459.67) this.temperature = temperature; else throw new IllegalArgumentException(); } /* * Getter method to retrieve the scale (Celsius or Fahrenheit) */ public String getScale() { return scale.toLowerCase(); } /* * Setter method to set the scale (Celsius or Fahrenheit) */ public void setScale(String scale) { if (scale.toLowerCase().equals("celsius") || scale.toLowerCase().equals("fahrenheit")) { this.scale = scale.toLowerCase(); } else throw new IllegalArgumentException(); } /* * Method to convert temperature to Celsius */ public double toCelsius() { if (scale.equals("fahrenheit")) { return (temperature - 32) * 5 / 9; } else { return temperature; // If already in Celsius, return the temperature value } } /* * Method to convert temperature to Fahrenheit */ public double toFahrenheit() { if (scale.equals("celsius")) { return (temperature * 9 / 5) + 32; } else { return temperature; // If already in Fahrenheit, return the temperature value } } }