Method does not correctly show expected result

1

I have this interface

public interface Promocional {

    boolean aplicaDesconto(double porcentagem);

    default boolean aplicaDescontoDe10Porcento() {
        return aplicaDesconto(0.1);
    }
}

The class LivroFisico that extends the superclass Livro and implements the interface Promocional

public class LivroFisico  extends Livro implements Promocional{
    public LivroFisico(Autor autor) {
        super(autor);
    }

    @Override
    public boolean aplicaDesconto(double porcentagem) {
        // TODO Auto-generated method stub
        return true;
    }

}

And here in method main it does not display properly.

main ()

LivroFisico fisico = new LivroFisico(autor);
fisico.setValor(59.90);
if(fisico.aplicaDescontoDe10Porcento()) {
        System.out.println("Valor agora e: " + fisico.getValor());
    }

It displays 59.90 and not 53.91 which is the discounted value.

I believe that in the class LivroFisico that it is mandatory to use the method, is giving error.

    
asked by anonymous 01.08.2015 / 06:01

2 answers

2

You have two problems.

Your problem is recurring nowadays. Most people learn to program by methods I do not understand. It seems to be a thing of following recipes and not learning the concepts, the working of what you are using. Even being full of information about it in books, tutorials, blogs, and even here in several questions. I myself I replied a few hours ago about C # , but the problem holds for all languages. Just follow everyone links to learn about it.

The most specific answer in Java is here .

In short: the processor for better performance treats data types float and double in binary form and therefore can not represent all numbers with decimals, there is the so-called rounding problem and there is nothing to it can be done other than using the correct type of data when dealing with monetary values or representing something else that needs accuracy. This type is Bigdecimal .

In addition, your discount method ( aplicaDesconto() ) is not doing any operations. He does not calculate any discount.

    
01.08.2015 / 06:14
1

A quick and easy way to resolve this is to change your application's method accordingly:

public boolean aplicaDesconto(double porcentagem) {
        setValor(getValor() - (getValor()*porcentagem))
        return true;
    }

This will make it actually multiply the value. Remember to create the gets and sets of value.

public Double getValor() {
    return valor;
}

public void setValor(Double valor) {
    this.valor = valor;
}
    
01.08.2015 / 06:28