brainfrz

Untitled

Oct 25th, 2015
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. public class TempConverter {
  2.     public enum TEMP_TYPE {
  3.         Celsius, Fahrenheit;
  4.     }
  5.  
  6.     private final static TEMP_TYPE DEFAULT_TEMP_TYPE = TEMP_TYPE.Celsius;
  7.     private final TEMP_TYPE convertingFrom, convertingTo;
  8.  
  9.     public TempConverter(TEMP_TYPE convertFrom) {
  10.         convertingFrom = convertFrom;
  11.  
  12.         if (convertFrom == TEMP_TYPE.Celsius) {
  13.             convertingTo = TEMP_TYPE.Fahrenheit;
  14.         }
  15.         else if (convertFrom == TEMP_TYPE.Fahrenheit) {
  16.             convertingTo = TEMP_TYPE.Celsius;
  17.         }
  18.         else {
  19.             convertingTo = DEFAULT_TEMP_TYPE;
  20.         }
  21.     }
  22.  
  23.  
  24.  
  25.     public int convertTemp(double fromTemp) {
  26.         int toTemp = 0;
  27.  
  28.         if (convertingFrom == TEMP_TYPE.Fahrenheit) {
  29.             toTemp = (int)(Math.round((fromTemp - 32) * (5.0 / 9.0)));
  30.         }
  31.         else if (convertingFrom == TEMP_TYPE.Celsius) {
  32.             toTemp = (int)(Math.round(fromTemp * 1.8 + 32));
  33.         }
  34.         else {
  35.             throw new TempTypeDoesntExistException("Temperature type isn't supported.");
  36.         }
  37.  
  38.         return toTemp;
  39.     }
  40.  
  41.  
  42.  
  43.     public TEMP_TYPE fromTempType() {
  44.         return convertingFrom;
  45.     }
  46.  
  47.     public TEMP_TYPE toTempType() {
  48.         return convertingTo;
  49.     }
  50.  
  51.     public String fromTempTypeStr() {
  52.         return convertingFrom.toString();
  53.     }
  54.  
  55.     public String toTempTypeStr() {
  56.         return convertingTo.toString();
  57.     }
  58.  
  59.  
  60.  
  61.  
  62.     public static class TempTypeDoesntExistException extends IndexOutOfBoundsException {
  63.         public TempTypeDoesntExistException() { }
  64.  
  65.         public TempTypeDoesntExistException(String message) {
  66.             super(message);
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment