Does anyone know how to make a unit converter with java using if, else, else if; .equals?
For example:
2.0 miles equals:
321868.8 centimeters
3218.688 meters
3.218688 kilometers
|||I would pick a base unit to start. Then I would convert the entered number to the base unit and then to the desired one. For example, lets say you choose meters as the base unit.
First, I would define several constants to convert to meters.
static double KILOMETERS = 0.001;
static double CENTIMETERS = 100;
static double MILES = 0.00062;
static double INCHES = 39.37;
Then, declare the variables.
String start_type , end_type;
double start_value , base_value, end_value;
After storing the type of conversion, I would put the if-else statements to convert to the base.
if(start=="miles") {
base_value = MILES*start_value;
}
else if(start=="centimeters") {
base_value = CENTIMETERS*start_value;
}
...
Finally, put the if-else statements to convert to the end type.
if(end=="miles") {
end_value = 1/MILES * base_value;
}
else if(end=="centimeters") {
end_value = 1/CENTIMETERS * base_value;
}
...
Hope this helps. Good Luck.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment