Java Program: How to convert Units?

In this program you will see, way to convert one length measuring unit to another unit.Generally such type of questions asked to check programming logics.

See Also : Java Program : Convert time hour minute and seconds

Example

import java.util.Scanner;

public class UnitConversionCalculator {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

	      System.out.println("Convert from:");
	      String fromUnit = in.nextLine();
	      UnitConverter from = new UnitConverter(fromUnit);

	      System.out.println("Convert to: ");
	      String toUnit = in.nextLine();
	      UnitConverter to = new UnitConverter(toUnit);

	      System.out.println("Value:");
	      double val = in.nextDouble();
	      //convert to meter
	      double meters = from.toMeters(val);
          //convert meter to required unit
	      double converted = to.fromMeters(meters);

	      System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
	}

}

That is main class for unit conversion for length measurement.

public class UnitConverter {
	static double INCHES = 39.37;
	static double FEET = 3.28;
	static double MILES = 0.00062;
	static double MILLIMETERS = 1000;
	static double CENTIMETERS = 100;
	static double METERS = 1;
	static double KILOMETERS = 0.001;

	private double meters, converted;

	String fromUnit, toUnit;

	public UnitConverter(String afromUnit) {
		fromUnit = afromUnit;
		toUnit = afromUnit;
	}

	// method to convert given value to meter
	public double toMeters(double val) {
		if (toUnit.equals("in")) {
			meters = (val / INCHES);
		} else if (toUnit.equals("ft")) {
			meters = (val / FEET);
		} else if (toUnit.equals("mi")) {
			meters = (val / MILES);
		} else if (toUnit.equals("mm")) {
			meters = (val / MILLIMETERS);
		} else if (toUnit.equals("cm")) {
			meters = (val/ CENTIMETERS);
		} else if (toUnit.equals("m")) {
			meters = (val / METERS);
		} else {
			meters = (val / KILOMETERS);
		}
		return meters;
	}

	// method to convert meter to required unit
	public double fromMeters(double meters) {
		if (fromUnit.equals("in")) {
			converted = Math.round(INCHES * 100 * meters);
		} else if (fromUnit.equals("ft")) {
			converted = Math.round(FEET * 100 * meters);
		} else if (fromUnit.equals("mi")) {
			converted = Math.round(MILES * 100 * meters);
		} else if (fromUnit.equals("mm")) {
			converted = Math.round(MILLIMETERS * 100 * meters);
		} else if (fromUnit.equals("cm")) {
			converted = Math.round(CENTIMETERS * meters);
		} else if (fromUnit.equals("m")) {
			converted = Math.round(METERS * meters);
		} else {
			converted = Math.round(KILOMETERS * meters);
		}
		return converted;
	}
}

Output


Convert from:
m
Convert to: 
cm
Value:
1
1.0 m = 100.0 cm