Reputation: 233
I am trying to make a method that will convert any unit to any larger unit. I need to, I'm guessing provide parameters for each input, so I'm guessing it needs to ask the user parameters for..startingNum, conversionFactor, outPutNum, but I'm unsure where to begin. I already made one with inches:
public Convertor()
{
inches=0;
feet=0;
yards=0;
leftoverInches=0;
}
/**
* Mutator method to convert inches to feet
*/
public void convertValuesInchtoFeet(int anyInches)
{
inches=anyInches;
feet=anyInches/12;
leftoverInches= anyInches%12;
System.out.println(inches+" inches = " +feet+" feet.");
System.out.println("There are " +leftoverInches +" leftover inches");
}
Please help! Thanks.
Upvotes: 2
Views: 6527
Reputation: 11
Consider to use UCUM (Unified Code for Units of Measure). This can help to develop a converter in Java. What UCUM is, is explained by UCUM itself with:
The Unified Code for Units of Measure (UCUM) is a code system intended to include all units of measures being contemporarily used in international science, engineering, and business.
I have used UCUM for my project: calculate.plus
Upvotes: 1
Reputation: 26809
Create enum:
enum Unit {
INCHES, FEETS, YARDS
}
And your amount class:
class Amount {
private Unit unit;
private double amount;
//getters and setters
}
And main parts: factorsMap which has two parameters (source unit, destination unit) connected with some value:
sourceUnit * value = destinationUnit,
then convert method looks like this:
public void convert(Amount source, Amount destination) {
double factor = factorsMap.get(source.getUnit(), destination.getUnit());
destination.setAmount(source.getAmount() * factor);
}
Upvotes: 1
Reputation: 35405
Use Enums to store the various unit names. e.g,
public Enum Unit {
MM, CM, INCH, FEET;
}
Follow the Planets example in the above page. You can create a property called number of millimeters for each unit (assuming millimeters is your smallest unit) and a function getNumberOfMillimeters() to return it. So, CM.getNumberOfMillimeters() would return 10 and so on for each unit. Then, you can create a generic function like this:
public double convert(Unit unit1, Unit unit2, double input) {
return input*(unit2.getNumberOfMillimeters()/unit1.getNumberOfMillimeters());
}
I hope it helps. Comment if you find any difficulty in following it.
Upvotes: 2
Reputation: 559
Any unit to any unit is a bit vague, but generally you need to provide: a) input number b) input unit c) output unit
Assuming you want to make a function that does general conversion between feet, inches and yards.
I'd take a look at the TimeUnit API and see if you get any ideas on a different way of doing it. Its made using enumerations with methods in them, but I don't know how familiar you are with Enums.
Oh yeah, TimeUnit is used like this:
TimeUnit.SECONDS.toMillis(1); // Returns 1000
Upvotes: 3