Skip to content

Instantly share code, notes, and snippets.

@jnskender
Created March 16, 2014 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnskender/9588173 to your computer and use it in GitHub Desktop.
Save jnskender/9588173 to your computer and use it in GitHub Desktop.
package unit.converter;
import java.util.Scanner;
/**
*
* @author Nick
*/
public class UnitConverter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.next();
System.out.print("Convert to: ");
String toUnit = in.next();
UnitConversions myIn = new UnitConversions(fromUnit);
UnitConversions myOut= new UnitConversions(toUnit);
System.out.print("What is the value you would like to convert: ");
double inValue = in.nextFloat();
double mmValue =myIn.toMM(inValue);
double converted = myOut.toUnit(mmValue);
System.out.println(inValue + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
package unit.converter;
/**
*
* @author Nick
*/
public class UnitConversions {
private double inValue, mm;
String fromUnit;
String toUnit;
public UnitConversions(String afromUnit)
{
fromUnit = afromUnit;
toUnit = afromUnit;
}
public double toMM(double inValue)
{
if (fromUnit.equalsIgnoreCase("in"))
{
inValue = (inValue * 25.4);
}
else if(fromUnit.equalsIgnoreCase("ft"))
{
inValue = (inValue * 304.8);
}
else if (fromUnit.equalsIgnoreCase("mi"))
{
inValue = (inValue * 1609344);
}
else if (fromUnit.equalsIgnoreCase("cm"))
{
inValue = (inValue * 10);
}
else if (fromUnit.equalsIgnoreCase("m"))
{
inValue = (inValue / 1000);
}
else if (fromUnit.equalsIgnoreCase("km"))
{
inValue = (inValue * 1000)*1000;
}
else if (fromUnit.equalsIgnoreCase("mm"))
{
inValue = inValue;
}
else
{
System.out.println("Beginning unit not supported");
}
return inValue;
}
public double toUnit(double inValue)
{
if (toUnit.equalsIgnoreCase("in"))
{
inValue = (inValue / 25.4);
}
else if(toUnit.equalsIgnoreCase("ft"))
{
inValue = (inValue / 304.8);
}
else if (toUnit.equalsIgnoreCase("mi"))
{
inValue = (inValue / 1609344);
}
else if (toUnit.equalsIgnoreCase("cm"))
{
inValue = (inValue / 10);
}
else if (toUnit.equalsIgnoreCase("m"))
{
inValue = (inValue / 1000);
}
else if (toUnit.equalsIgnoreCase("km"))
{
inValue = (inValue / 1000)/1000;
}
else if (toUnit.equalsIgnoreCase("mm"))
{
inValue = inValue;
}
else
{
System.out.println("Ending unit not supported. ");
}
return inValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment