Lab 1
Description: This is a program to generate temperature simulations and record related statistics. The work is divided into 4 classes with responsibilities as follows:
TemperatureSensorApp – Interacts with the user (including input error detection) and manages the other classes.
Temperature – A data type with a value in Celsius, Fahrenheit or Kelvin.
TemperatureSimulator – Generates uniformly distributed random numbers within the upper and lower bounds for each season.
TemperatureRecord – Stores all the temperatures generated in a session and computes useful statistics on the data set.
Code:
import java.io.InputStream; import java.util.InputMismatchException; import java.util.Scanner; // //A temperature sensor simulation app. // public class TemperatureSensorApp { private static enum MenuOption{ WINTER, SPRING, SUMMER, FALL, EXIT; } public static class InvalidInputException extends Exception{ /** * */ private static final long serialVersionUID = 2219064286279606513L; InvalidInputException(String msg){ super(msg); } } public static void main(String args[]){ boolean done = false; int userInput; int numSimulations = 0; MenuOption selection = MenuOption.EXIT; TemperatureRecord record; TemperatureSimulator tempSim = new TemperatureSimulator(); //Display the welcome message. displayWelcome(System.in); do{ //Display menu to user and get input try{ System.out.println(); userInput = displayMenu(System.in); userInput = userInput- 1; //Shift input so that it is zero aligned. //Assign the MenuOption that corresponds to the user's input. //This will throw ArrayIndexOutOfBoundsException if userInput does not match //a valid MenuOption value. selection = MenuOption.values()[userInput]; if(selection != MenuOption.EXIT){ //Ask how man simulations to run. numSimulations = getNumSimulations(System.in); record = runSimulations(numSimulations, selection, tempSim); //Display Temperature Statistics to user. System.out.println("Statistics for " + selection + " season:"); System.out.println("First temp: " + record.getFirst()); System.out.println("Last temp: " + record.getLast()); System.out.println("Highest temp: " + record.getHighest()); System.out.println("Lowest temp: " + record.getLowest()); System.out.println("Sum: " + record.getSum()); System.out.println("Average temp: " + record.getAvg()); } else{ System.out.println("Goodbye."); done = true; } } catch(InvalidInputException e){ System.err.println("Invalid selection. Please try again."); done = false; } catch(ArrayIndexOutOfBoundsException e){ System.err.println( "Unexpected array index out of bounds while accessing" + " MenuOption.values(). Program will terminate."); done = true; } }while(!done); } // //Display a welcome screen to the user. // private static void displayWelcome(InputStream istream){ System.out.println("Welcome to Season Sim®"); } // //Display the menu options to user and returns the users selection. // //Returns: //1 - Winter Sim //2 - Spring Sim //3 - Summer Sim //4 - Fall Sim //5 - Exit @SuppressWarnings("resource") private static int displayMenu(InputStream istream) throws InvalidInputException{ Scanner in = new Scanner(istream); int selection = 0; System.out.println("Please select one of the following simulations:"); System.out.println(" for Winter simulation."); System.out.println(" for Spring simulation."); System.out.println(" for Summer simulation."); System.out.println(" for Fall simulation."); System.out.println("or to exit the program."); System.out.print(": "); try{ selection = in.nextInt(); if(selection < 1 || selection > 5){ throw new InvalidInputException("Selection: \"" + selection + "\" " + "falls outside valid range of: 1-5 (inclusive)"); } } catch(InputMismatchException e){ throw new InvalidInputException("Input was not an integer."); } return selection; } @SuppressWarnings("resource") private static int getNumSimulations(InputStream istream) throws InvalidInputException{ int numSimulations = 0; System.out.println("Enter the number of simulations to run: "); Scanner in = new Scanner(istream); try{ numSimulations = in.nextInt(); if(numSimulations<=0){ throw new InvalidInputException("Input must be greater than zero."); } } catch(InputMismatchException e){ throw new InvalidInputException("Input was not an integer."); } return numSimulations; } // //Runs a specified number of Temperature simulations and returns a record of the runs. // private static TemperatureRecord runSimulations(int numSims, MenuOption selection, TemperatureSimulator tempSim){ double temp = 0; TemperatureRecord record = new TemperatureRecord(); for(int i=0; i<numSims; i++){ switch(selection){ case WINTER: temp = tempSim.getWinterTemp(); break; case SPRING: temp = tempSim.getSpringTemp(); break; case SUMMER: temp = tempSim.getSummerTemp(); break; case FALL: temp = tempSim.getFallTemp(); break; case EXIT: System.err.println("Invalid option \'EXIT\' for simulation."); break; default: System.err.println("Unrecognized option for simulation."); } if(selection != MenuOption.EXIT){ record.add(new Temperature(temp,Temperature.Units.FAHRENHEIT)); } } return record; } }
import java.text.DecimalFormat; // //This class implements a temperature data type. // public class Temperature implements Comparable{ public enum Units { CELSIUS, FAHRENHEIT, KELVIN; }; public static class InvalidTemperatureUnitException extends Exception{ /** * */ private static final long serialVersionUID = 3755108601677734615L; InvalidTemperatureUnitException(String message){ super(message); } } private double temp; //Temperature in degrees Celsius. private Units displayUnits; //Unit's to display //Default Constructor public Temperature(){ setTemperature(0.0,Units.CELSIUS); } // //Constructor sets the temperature to the parameter. //Note: newTemp is assumed to be in units specified by newUnits and will be converted to //Celsius if newUnits != Units.Celsius. // public Temperature(double newTemp, Units newUnits){ setTemperature(newTemp,newUnits); } // //Initialization Constructor. //Note: newTemp is assumed to be in units specified by newUnits and will be converted to //Celsius if newUnits != Units.Celsius. // public Temperature(double newTemp, String newUnits) throws InvalidTemperatureUnitException{ setTemperature(newTemp,newUnits); } // //Sets the temperature to newTemp. //Note: newTemp is assumed to be in units of newUnits. // public void setTemperature(double newTemp, Units newUnits){ displayUnits = newUnits; switch(displayUnits){ case CELSIUS: temp = newTemp; break; case FAHRENHEIT: temp = fahrenheitToCelsius(newTemp); break; default: temp = kelvinToCelsius(newTemp); } } // //Sets the temperature to newTemp. //Note: newTemp is assumed to be in units of stringNewUnits. // public void setTemperature(double newTemp, String stringNewUnits) throws InvalidTemperatureUnitException{ try{ Units newUnits = Units.valueOf(stringNewUnits); setTemperature(newTemp, newUnits); } catch(IllegalArgumentException e){ String message = "\""+stringNewUnits+"\"" + "is not a valid temperature unit."; throw new InvalidTemperatureUnitException(message); } } // //Returns the value of temperature in units specified by displalyUnits. // public double getTemperature(){ double t; switch(displayUnits){ case FAHRENHEIT: t = celsiusToFahrenheit(temp); break; case KELVIN: t = celsiusToKelvin(temp); default: t = temp; } return t; } // //Returns the value of temperature in units specified by the units parameter. // public double getTemperature(Units units){ double t; switch(units){ case KELVIN: t = celsiusToKelvin(temp); break; case FAHRENHEIT: t = celsiusToFahrenheit(temp); break; default: t = temp; } return t; } // //Accessor. // public Units getUnits(){ return displayUnits; } // //Returns a temperature whose value is the sum of this and rightOp and has the same units //as this. // public Temperature add(Temperature rightOp){ //Compute the sum using the units of left operand. double sum = this.getTemperature() + rightOp.getTemperature(displayUnits); return new Temperature(sum, displayUnits); } // //A string representation of this. // @Override public String toString(){ double value; String unitsAsString; switch(displayUnits){ case FAHRENHEIT: value = celsiusToFahrenheit(temp); unitsAsString = "°F"; break; case KELVIN: value = celsiusToKelvin(temp); unitsAsString = "K"; break; default: value = temp; unitsAsString = "°C"; } return new DecimalFormat("##.#").format(value) + unitsAsString; } // //Compares this to another Temperature and returns: //-1 if this < t. //+1 if this > t. //0 if this == t. // @Override public int compareTo(Temperature t) { int compare; if(t == null){ throw new NullPointerException(); } else if(getTemperature() < t.getTemperature(displayUnits)){ compare = -1; } else if(getTemperature() > t.getTemperature(displayUnits)){ compare = 1; } else{ compare = 0; } return compare; } private double celsiusToFahrenheit(double celsius){ double fahrenheit = celsius * 180/100 + 32; return fahrenheit; } private double fahrenheitToCelsius(double fahrenheit){ double celsius = (fahrenheit - 32) * 100/180; return celsius; } private double celsiusToKelvin(double celsius){ double kelvin = celsius + 273; return kelvin; } private double kelvinToCelsius(double kelvin){ double celsius = kelvin - 273; return celsius; } }
import java.util.Random; // //A class to simulate seasonal temperatures. // public class TemperatureSimulator { //Spring simulating constants. public static final int WINTER_MIN = 20; public static final int WINTER_MAX = 40; public static final int SPRING_MIN = 40; public static final int SPRING_MAX = 70; public static final int SUMMER_MIN = 70; public static final int SUMMER_MAX = 90; public static final int FALL_MIN = 40; public static final int FALL_MAX = 60; //Random number generator. private Random rng; // //Default Constructor // public TemperatureSimulator(){ rng = new Random(); } // //Returns a random number between WINTER_MIN and WINTER_MAX (inclusive). // public int getWinterTemp(){ int rand = WINTER_MIN + rng.nextInt(WINTER_MAX-WINTER_MIN + 1); return rand; } // //Returns a random number between SPRING_MIN and SPRING_MAX (inclusive). // public int getSpringTemp(){ int rand = SPRING_MIN + rng.nextInt(SPRING_MAX-SPRING_MIN + 1);; return rand; } // //Returns a random number between SUMMER_MIN and SUMMER_MAX (inclusive). // public int getSummerTemp(){ int rand = SUMMER_MIN + rng.nextInt(SUMMER_MAX-SUMMER_MIN + 1);; return rand; } // //Returns a random number between FALL_MIN and FALL_MAX (inclusive). // public int getFallTemp(){ int rand = FALL_MIN + rng.nextInt(FALL_MAX-FALL_MIN + 1);; return rand; } }
import java.util.LinkedList; // //This class maintains a record of temperatures and related statistics. // public class TemperatureRecord extends LinkedList{ /** * */ private static final long serialVersionUID = -9095126012449179697L; // //Returns the highest Temperature in this record. // public Temperature getHighest(){ Temperature highest = null; for(Temperature t : this){ if( (highest == null) || ( highest.compareTo(t) < 0 ) ){ highest = t; } } return highest; } // //Returns the lowest Temperature in this record. // public Temperature getLowest(){ Temperature lowest = null; for(Temperature t : this){ if( (lowest == null) || ( lowest.compareTo(t) > 0 ) ){ lowest = t; } } return lowest; } // //Returns the sum of all Temperatures in this record. // public Temperature getSum(){ Temperature sum = null; for(Temperature t : this){ if(sum != null){ sum = sum.add(t); } else{ sum = t; } } return sum; } // //Returns the avg of all Temperatures in this record. // public Temperature getAvg(){ Temperature sum = getSum(); double avg = sum.getTemperature() / size(); return new Temperature(avg, sum.getUnits()); } }
Screenshots:
Leave a Reply