package cse1030; import java.util.Collection; /** * The class DistanceUtility contains constants and * methods to convert between kilometres and miles. * * @author CSE1030Z */ public class DistanceUtility { /** * The number of kilometres in a mile. */ public static final double KILOMETRES_PER_MILE = 1.609344; /** * Converts distances in kilometres to miles. * * @param km The distance to convert. If km * is negative then the returned distance is * also negative. * @return Distance in miles. */ public static double kilometresToMiles(double km) { double result = km / KILOMETRES_PER_MILE; return result; } /** * Converts distances in kilometres to miles for arrays. * If an element of the array argument is negative the * corresponding element of the returned array is also * negative. * * @param km The distances to convert. * @pre. km.length > 0 * @return Distances in miles in an array with * length == km.length. */ public static double[] kilometresToMiles(double[] km) { double miles[] = new double[km.length]; for (int i = 0; i < km.length; i++) { miles[i] = kilometresToMiles(km[i]); } return miles; } /** * Converts distances in kilometres to miles for a Collection. * If an element of the collection is negative the * corresponding element of the returned array is also * negative. * * @param km The distances to convert. * @pre. km.size() > 0 * @return Distances in miles in an array with * length == km.size(). */ public static double[] kilometresToMiles(Collection km) { double[] miles = new double[km.size()]; int i = 0; for (Number n : km) { miles[i] = kilometresToMiles(n.doubleValue()); i++; } return miles; } private DistanceUtility() { // private constructor to prevent instantiation } }