package franck.eecs1030; import java.util.HashMap; import java.util.Map; /** * Converts amounts between different units. * * @author Franck van Breugel */ public class Converter { /** * The constant that represents the unit of centimeters. */ public static final int CENTIMETER = 1; /** * The constant that represents the unit of feet. */ public static final int FOOT = 4; /** * The constant that represents the unit of inches. */ public static final int INCH = 3; /** * The constant that represents the unit of meters. */ public static final int METER = 2; private static Map> factor = new HashMap>(); static { final double CENTIMETERS_PER_METER = 100.0; final double CENTIMETERS_PER_INCH = 2.54; final double CENTIMETERS_PER_FOOT = 30.48; final double INCHES_PER_FOOT = 12.0; Map map = new HashMap(); map.put(Converter.CENTIMETER, 1.0); map.put(Converter.METER, 1.0 / CENTIMETERS_PER_METER); map.put(Converter.INCH, 1.0 / CENTIMETERS_PER_INCH); map.put(Converter.FOOT, 1.0 / CENTIMETERS_PER_FOOT); Converter.factor.put(Converter.CENTIMETER, map); map = new HashMap(); map.put(Converter.CENTIMETER, CENTIMETERS_PER_METER); map.put(Converter.METER, 1.0); map.put(Converter.INCH, CENTIMETERS_PER_METER / CENTIMETERS_PER_INCH); map.put(Converter.FOOT, CENTIMETERS_PER_METER / CENTIMETERS_PER_FOOT); Converter.factor.put(Converter.METER, map); map = new HashMap(); map.put(Converter.CENTIMETER, CENTIMETERS_PER_INCH); map.put(Converter.METER, CENTIMETERS_PER_INCH / CENTIMETERS_PER_METER); map.put(Converter.INCH, 1.0); map.put(Converter.FOOT, 1.0 / INCHES_PER_FOOT); Converter.factor.put(Converter.INCH, map); map = new HashMap(); map.put(Converter.CENTIMETER, CENTIMETERS_PER_FOOT); map.put(Converter.METER, CENTIMETERS_PER_FOOT / CENTIMETERS_PER_METER); map.put(Converter.INCH, INCHES_PER_FOOT); map.put(Converter.FOOT, 1.0); Converter.factor.put(Converter.FOOT, map); } private Converter() {} /** * Converts the given amount from the given unit to the other given unit. * * @param amount the amount to be converted. * @pre. amount >= 0 * @param from the unit of the amount. * @pre. from == Converter.CENTIMETER || from == Converter.METER || from == Converter.INCH || from == Converter.FOOT * @param to the unit to which the amount is converted. * @pre. to == Converter.CENTIMETER || to == Converter.METER || to == Converter.INCH || to == Converter.FOOT * @return the given amount converted from the given unit to the other given unit. * @throws IllegalArgumentException if the amount is too big so that it causes an overflow. */ public static double convert(double amount, int from, int to) throws IllegalArgumentException { double converted = amount * Converter.factor.get(from).get(to); if (converted == Double.POSITIVE_INFINITY) // overflow { throw new IllegalArgumentException(); } else { return converted; } } }