Compare prices taking into account units (kg, g)

Asked

Viewed 1,315 times

3

Hello, I need to compare 2 products, taking into account their weight and values, to know which product is more advantageous to buy.

Ex: Rice 5kg - R$ 10,00 Rice 2kg - R$ 6,00

Thinking that you can compare grams to kg, making the correct conversion. I am beginner in programming for Android and I will be very grateful for the help.

The layout part I already understand, I really need it from Mainactivity. In the image shows more or less how it will look at the end.

I am not able to do this calculation. How do I check if the chosen unit is 'g' or 'kg', 'l', 'ml' and how to do the conversion based calculation

inserir a descrição da imagem aqui

My Activity is like this at the moment, remembering that I’m starting in mobile development and I’m really enjoying it.

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Button b = (Button) findViewById(R.id.b);
    b.setOnClickListener(new View.OnClickListener(){

        public void onClick (View v) {

            //unidades
            Spinner peso1 = (Spinner) findViewById(R.id.spinner1);
            Spinner peso2 = (Spinner) findViewById(R.id.spinner2);

            //quantidade em unidades
            EditText qtd1 = (EditText) findViewById(R.id.qtd1);
            EditText qtd2 = (EditText) findViewById(R.id.qtd2);

            //valor do produto
            EditText valor1 = (EditText) findViewById(R.id.valor1);
            EditText valor2 = (EditText) findViewById(R.id.valor2);

            Double resultado1;
            Double resultado2;

            Double vlr1 = Double.parseDouble(valor1.getText().toString());
            Double vlr2 = Double.parseDouble(valor2.getText().toString());

            Integer quantidade1 = Integer.parseInt(qtd1.getText().toString());
            Integer quantidade2 = Integer.parseInt(qtd2.getText().toString());

            //deve fazer as conversão para o cálculo
            if (peso1.getSelectedItem().toString().equals("g"){
                quantidade1 = quantidade1 * 0.001; //converte pra kg

            }
            if (peso2.getSelectedItem().toString().equals("g"){
                quantidade2 = quantidade2 * 0.001;/ //converte pra kg

            }

            resultado1 = quantidade1 * vlr1;
            resultado2 = quantidade2 * vlr2;


            if (quantidade1 > quantidade2 || resultado1 < resultado2) {

                Toast.makeText(getApplicationContext(), "Compre o produto tal", Toast.LENGTH_SHORT).show();

            }
            else if (quantidade1 < quantidade2 || resultado1 > resultado2) {

                Toast.makeText(getApplicationContext(), "Compre o produto tal", Toast.LENGTH_SHORT).show();
            }
            else{
                 Toast.makeText(getApplicationContext(), "A vantagem dos produtos é a mesma", Toast.LENGTH_SHORT).show();
            }
            if (quantidade1 == quantidade2){
                Toast.makeText(getApplicationContext(), "Mesma quantidade", Toast.LENGTH_SHORT).show();
            }

        }
    });

}

}

  • 5

    Post the code of Activity that you have, helps contextualize and facilitates in the construction of the answer.

  • The difficulty is in calculating or obtaining form values?

  • Yes, my difficulty is to understand how this calculation is done in view of the values informed.

  • @Fláviaamaral looking like this looks like you made the correct algorithm. Did you have any error? Where exactly is your doubt?

  • I am not able to do this calculation. How do I check if the chosen unit is 'g' or 'kg', 'l', 'ml' and how to do the conversion based calculation.

  • 1

    @Fláviaamaral you’ve done it here: if(peso1.getSelectedItem().toString().equals("g")){quantidade1 = quantidade1 * 0.001;}

  • Already, already yes. It’s there in the codes above. Am I doing it right and even I don’t know? Rs

  • @Fláviaamaral I believe that you have solved the problem yes :) except for the fact that there was a missing parentheses before the key, but if that’s what your code wouldn’t even compile. Notice my comment up there )) after the equals.

  • Converting L/mL to kg/g would be a little more complicated. You cannot calculate without knowing the density of the product. 1 liter of water weighs 1kg, but 1 liter of something else can weigh more, or less, than that.

  • vc can see the calculation in rotasul.net/tools/comparator.php by the way I always use this page, even offline []’s

Show 5 more comments

1 answer

7


You can do this using an Object-Oriented approach to encapsulate the complexity of these accounts.

Building a Product Model

First you can create a Enum for each measuring scale.

For example, for weight:

public enum UnidadePeso implements UnidadeProporcional {
    Grama(1), Kilograma(1000), Tonelada(1000000);

    private int proporcao;

    private UnidadePeso(int proporcao) {
        this.proporcao = proporcao;
    }

    @Override
    public int proporcao() {
        return proporcao;
    }
}

And for volume:

public enum UnidadeVolume implements UnidadeProporcional {
    Mililitro(1), Litro(1000);

    private int proporcao;

    private UnidadeVolume(int proporcao) {
        this.proporcao = proporcao;
    }

    @Override
    public int proporcao() {
        return proporcao;
    }
}

The interface UnidadeProporcional serves to generalize the method proporcao():

public interface UnidadeProporcional {

    int proporcao();

}

Finally, here is a generic class of Produto which receives the unit value, quantity and unit of measurement and allows comparison between them:

public class Produto<T extends UnidadeProporcional> implements Comparable<Produto<T>> {

    private BigDecimal preco;
    private int quantidade;
    private T unidade;

    public Produto(BigDecimal preco, int quantidade, T unidade) {
        if (preco == null) {
            throw new IllegalArgumentException("Preço nulo!");
        }
        if (quantidade <= 0) {
            throw new IllegalArgumentException("Quantidade deve ser um inteiro positivo!");
        }
        if (unidade == null) {
            throw new IllegalArgumentException("Informe a unidade!");
        }
        this.preco = preco;
        this.quantidade = quantidade;
        this.unidade = unidade;
    }

    public BigDecimal getPreco() {
        return preco;
    }

    /**
     * Retorna o preço na unidade básica para possibilitar a comparação em unidades diferentes.
     * Por exemplo, se a unidade for kg, o "preço base" será dividido por 1000, ou seja, o valor em gramas do produto.
     * Além disso, o resultado também será dividido pela quantidade, de forma que o resultado seja o valor por grama. 
     */
    public BigDecimal getPrecoBase() {
        return preco.divide(new BigDecimal(unidade.proporcao())).divide(new BigDecimal(quantidade));
    }

    public int getQuantidade() {
        return quantidade;
    }

    public T getUnidade() {
        return unidade;
    }

    @Override
    public int compareTo(Produto<T> o) {
        if (o == null) {
            throw new IllegalArgumentException("Objeto nulo!");
        }
        return this.getPrecoBase().compareTo(o.getPrecoBase());
    }

}

The method getPrecoBase() does the "magic", returning the price of the product in the basic unit of the scale.

For example, if the unit of the product is Kg and quantity 2, it divide the value by 1000 to turn the unit into grams and dpeois by 2 to get the value of one gram.

Therefore, it normalizes the values enabling comparison.

Example of use

With the built model, you can simply create two products and compare them:

Produto<UnidadePeso> laranjaExtra = new Produto<UnidadePeso>(
    new BigDecimal("50"), 1, UnidadePeso.Kilograma);

Produto<UnidadePeso> laranjaCarrefour = new Produto<UnidadePeso>(
    new BigDecimal("49.95"), 1000, UnidadePeso.Grama);

int resultado = laranjaExtra.compareTo(laranjaCarrefour);

If you have ever compared objects in Java with the method compareTo should know that a return 0 means that values are equal, 1 that the first is greater than the second and -1 to the contrary.

The code above will return 1 because the value per gram of orange in Extra goes out by R$ 0,05, while on the Carrefour goes by R$ 0,04995.

Improve my code

You can download or clone the project with the above code in my Github.

You can increment it, for example, to receive an amount of the type BigDecimal, since the user can enter with 1,5 litres or kilograms.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.