package franck.eecs1030; /** * 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 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 { final int CENTIMETERS_PER_METER = 100; final double CENTIMETERS_PER_INCH = 2.54; final double CENTIMETERS_PER_FOOT = 30.48; final int INCHES_PER_FOOT = 12; double converted; if (from == to) { converted = amount; } else if (from == Converter.CENTIMETER && to == Converter.METER) { converted = amount / CENTIMETERS_PER_METER; } else if (from == Converter.CENTIMETER && to == Converter.INCH) { converted = amount / CENTIMETERS_PER_INCH; } else if (from == Converter.CENTIMETER && to == Converter.FOOT) { converted = amount / CENTIMETERS_PER_FOOT; } else if (from == Converter.METER && to == Converter.CENTIMETER) { converted = amount * CENTIMETERS_PER_METER; } else if (from == Converter.METER && to == Converter.INCH) { converted = CENTIMETERS_PER_METER * amount / CENTIMETERS_PER_INCH; } else if (from == Converter.METER && to == Converter.FOOT) { converted = CENTIMETERS_PER_METER * amount / CENTIMETERS_PER_FOOT; } else if (from == Converter.INCH && to == Converter.CENTIMETER) { converted = amount * CENTIMETERS_PER_INCH; } else if (from == Converter.INCH && to == Converter.METER) { converted = amount * CENTIMETERS_PER_INCH / CENTIMETERS_PER_METER; } else if (from == Converter.INCH && to == Converter.FOOT) { converted = amount / INCHES_PER_FOOT; } else if (from == Converter.FOOT && to == Converter.CENTIMETER) { converted = amount * CENTIMETERS_PER_FOOT; } else if (from == Converter.FOOT && to == Converter.METER) { converted = amount * CENTIMETERS_PER_FOOT / CENTIMETERS_PER_METER; } else // from == Converter.FOOT && to == Converter.INCH { converted = amount * INCHES_PER_FOOT; } if (converted == Double.POSITIVE_INFINITY) // overflow { throw new IllegalArgumentException(); } else { return converted; } } }