Valueless results on variables, values added in Testemain class are not being used in Calculator class methods

Asked

Viewed 23 times

-1

public class Calculadora {
         
    public float valor1;
    public float valor2;
    public float valor3;
    
    public Calculadora(float valor1) {
        
    }
    
    public Calculadora(float valor1, float valor2){
        
    }
    
    public Calculadora(float valor1, float valor2, float valor3){
        
    }
 
    public float soma(){
        return valor1 + valor2 + valor3;
    }
    
    public float subtracao(){
        return valor1 - valor2 - valor3;
    }
    
    public float multiplicacao(){
        return valor1 * valor2 * valor3;
    }
    
    public float divisao(){
        return (valor1 / valor2 / valor3);
    }
}


public class TesteMain {

    public static void main(String[] args) {
        Calculadora c1 = new Calculadora(23, 32, 54);
        System.out.println("A soma dos n�meros �: " + c1.soma());
        System.out.println("A subtra��o dos n�meros �: " + c1.subtracao());
        System.out.println("A multiplica��o dos n�meros �: " + c1.multiplicacao());
        System.out.println("A divis�o dos n�meros �: " + c1.divisao());
    
    }

}
  • What is the result? Why not put the variables as parameters of the methods instead of attributes of the classes?

  • pq was thus specified in an exercise, I was able to run "this.valor1 = valor1;' and so with the other variables in the last constructor.

1 answer

0

You need to assign the values passed as parameters in the constructs to the private attributes of the class, so the methods will work successfully. The way it is at the moment methods are working with empty attributes, so in the summation method, for example, you are adding attributes without values.

The correct form of the third constructor of the class would be:

 public Calculadora(float valor1, float valor2, float valor3){
        this.valor1 = valor1;
        this.valor2 = valor2;
        this.valor3 = valor3;
 }

Browser other questions tagged

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