I am working on a program that should convert between in, ft, mi, mm, cm, m, and km. The question is:
Write a unit conversion program that asks users to identify the unit from which they want to convert and the unit to which they want to convert. Legal units are in, ft, mi, mm, cm, m, and km. Declare two objects of a class UnitConverter that convert between meters and a given unit.
Convert from:
in
Convert to:
mm
Value:
10
10 in = 254 mm
Use the following class as your main class:
import java.util.Scanner;
/**
This class converts between two units.
*/
public class ConversionCalculator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Convert from:");
String fromUnit = in.nextLine();
System.out.println("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.println("Value:");
double val = in.nextDouble();
double meters = from.toMeters(val);
double converted = to.fromMeters(meters);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
You need to supply the following class in your solution:
UnitConverter
Me and some of my fellow partners have been working on this for a good while and this is what we have come up with for the UnitConvert class.
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 val ,meters ,converted;
String fromUnit, toUnit;
public UnitConverter(String afromUnit)
{
fromUnit = afromUnit;
toUnit = afromUnit;
}
public double toMeters(double val)
{
if(toUnit.equals("in"))
{
meters = (1/INCHES);
}
else if(toUnit.equals("ft"))
{
meters = (1/FEET);
}
else if(toUnit.equals("mi"))
{
meters = (1/MILES);
}
else if(toUnit.equals("mm"))
{
meters = (1/MILLIMETERS);
}
else if(toUnit.equals("cm"))
{
meters = (1/CENTIMETERS);
}
else if(toUnit.equals("m"))
{
meters = (1/METERS);
}
else
{
meters = (1/KILOMETERS);
}
return meters;
}
public double fromMeters(double meters)
{
if(fromUnit.equals("in"))
{
converted = Math.round(meters*100*val);
}
else if(fromUnit.equals("ft"))
{
converted = Math.round(meters*100*val);
}
else if(fromUnit.equals("mi"))
{
converted = Math.round(meters*100*val);
}
else if(fromUnit.equals("mm"))
{
converted = Math.round(meters*100*val);
}
else if(fromUnit.equals("cm"))
{
converted = Math.round(CENTIMETERS*val);
}
else if(fromUnit.equals("m"))
{
converted = Math.round(METERS*val);
}
else
{
converted = Math.round(KILOMETERS*val);
}
return converted;
}
}
The code compiles and runs but when you try to do the inputs is just returns 10.0 in = 0.0 mm. The ConversionCalculator cannot be modified. Any help would be appreciated if you need more information please let me know I tried to supply everything I could think of.