Pergunta

I have taken this code from an example but I don't know how to calculate the value to Base Unit. This is the code for converting energy:

public enum U_EnergyConverter implements UnitConverter {
energy_calories {
    @Override
    public double toBaseUnit(double amount) {
        return amount;
    }

},
energy_joules {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 4.19;
    }
},
energy_kilocalories {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 0.001;
    }

};
public abstract double toBaseUnit(double amount);

public double toUnit(double baseUnitAmount) {
    return baseUnitAmount * (1 / (toBaseUnit(1)));
}

The Amounts I used in the code above are giving me wrong result. And I don't know from which source I can get the exact value for unit-conversion!!

Appreciate any help

Update: This is the mass unit code which is working very well:

public enum MassConverter implements UnitConverter {
mass_g {
    @Override
    public double toBaseUnit(double amount) {
        return amount;
    }

},
mass_kg {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 1000.00;
    }

},
mass_oz {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 28.3495231;
    }

},
mass_lb {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 453.59237;
    }

};
public abstract double toBaseUnit(double amount);

public double toUnit(double baseUnitAmount) {
    return baseUnitAmount * (1 / (toBaseUnit(1)));
}
Foi útil?

Solução

Change like this:

energy_kilocalories {
    @Override
    public double toBaseUnit(double amount) {
        return amount * 1000;
    }

};

toBaseUnit should return value in calories given the value in those units (such as joules, kilocalories etc). This is what the correct example does. Yours does the opposite.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top