This is what I am required to do using basic java programning, I am very new to this and was wondering if someone could help me out from what I have read in my book I am suppose to use if else and decision statements. What O dont understand is how to implement this program using the if else statements to convert between the different units.

Unit conversion. Write a unit conversion program that asks the users from which unit they want to convert (fl. oz, gal, oz, lb, in, ft, mi) and to which unit they want to convert (ml, l, g, kg, mm, cm, m, km). Reject incompatible conversions (such as gal → km). Ask for the value to be converted, then display the result: Convert from? gal Convert to? ml Value? 2.5 2.5 gal = 9462.5 ml


3 Years
Discussion Span
Last Post by thanatos2

well, first start by asking the user the unit that they're currently in:

System.out.println("What unit are you at?");
String unitFrom = scan.next();

then you could ask for the unit that they want to convert to:

System.out.println("What unit do you want to go to?");
String unitTo = scan.next();

now that you have both Strings, yo could brute force it and have a ton of if else statements, for example:

if (unitFrom.equals("oz") {
    //the user wants to go from oz to something, here, i can do my check to see if what the 
    //user wants to go to should be allowed!
    if (unitTo.equals("in") {
        //I can't go from oz to inches!!
    //a bunch more ifs here...

you could also use Enums but that may be out of the scope at this point.

Edited by thanatos2


Would I have to declare any of the units that are being converted or initialize anything?
Thank you so much for your help it actually makes a lot more sense now!


You don't need to declare any units, you could do what I did when comparing units


so if for example the user wrote a valid unit conversion (from meters to kilometers for example)
then you could have a method called meterToKilo that would take as a parameter the number of meters and it would return the equivalent in kilometers, something like:

//Returns the kilometer equivalent of the given length in meters.
public float metersToKilo(final float meters) {
    return meters / 1000;

you could have methods like that for each type of Unit.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.