Topics Index

Convert length from one unit to another

If you need explanation Read this topic

If you need Answer Take test on this topic

Write a program to convert length from one unit to another. Use only Inches, Centimeters, Feet, Meters, Kilometers, Miles for conversion and round off the result to two decimals. Return -1 if conversion is not possible. 1 feet=30.48 cms, 1 mt=3.2808 foot, 1 mile=1.6093 km.

Input (double, String, String) Output (double)
2.23, Kilometers, Centimeters 223000.0
21.65, Inches, Meters 0.55
68.5, Meters, Feet 224.74
56.22, Acre, Meters -1.0
6.5, Foot, Centimeters 198.12
86.4, Meters, Miles 0.05

class ConvertLengthToOtherUnit
    public static void main(String s[])
        double length = 6.5;
        String inputUnit = "Foot", outputUnit = "Centimeters";
        System.out.println("Converting " + length + " " + inputUnit + " to " + outputUnit + " we get " + convertToOtherUnit(length, inputUnit, outputUnit));


    public static double convertToOtherUnit(double length, String input, String output) {

Topic: Learn Arrays And Loops

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

To convert one unit into another we use one switch case
-- to check for input unit we use equals() method of String class.if it is foot control will move into the --> case "foot":
inside this case we check the output string if it is cm then outputunit=inputunit*30.48
else if the outputunit is mt then outputunit=inputunit/3.2808 we do it for all outputunits.
--for each input unit seprate cases will be written where inside each case there will be "else if" Ladder...
--to display the output unit upto two decimal we use "format()" method of  java.text.DecimalFormat  class as follows:
DecimalFormat df=new DecimalFormat("###,###.##);
--In else case we check whether outputString is invalid then  we return -1.

Posted by Mânïshå Mùlchåndânï    2014-12-30 12:32:33

This dose is now closed and the winners are . The 'lucky liker' is Asma Mujtaba Khan. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2015-01-03 05:09:45

© meritcampus 2019

All Rights Reserved.

Open In App