How do I get the methods to receive the x and y parameters?

1

When I request the values of x and y , I want to make the operations of the methods receive the values entered by the user. What to do?

public class Calculadora {
Scanner sc = new Scanner(System.in);

protected double x;
protected double y;
protected double soma;
protected double subt;
protected double mult;
protected double divs;


void setValores(){
    System.out.println("Informe dois valores: ");
    this.x = sc.nextDouble();
    this.y = sc.nextDouble();
}
void setSoma(double x, double y){
    this.soma = x + y;
}
double getSoma(){
    return soma;
}
void setSubt(double x, double y){
    this.subt = x-y;
}
double getSubt(){
    return subt;
}
void setMult(double x, double y){
    this.mult = x*y;
}
double getMult(){
    return mult;
}
void setDivs(double x, double y){
    this.divs = x/y;
}
double getDivs(){
    return divs;
}


void showValor(){
    System.out.println("soma: " + this.soma);
}
}
    
asked by anonymous 10.11.2017 / 13:47

1 answer

2

I imagine this is what you want:

import java.util.Scanner;

class Ideone {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Informe dois valores: ");
        Calculadora calc = new Calculadora(sc.nextDouble(), sc.nextDouble());
        System.out.println(calc.soma());
        System.out.println(calc.subtracao());
        System.out.println(calc.multiplicacao());
        System.out.println(calc.divisao());
    }
}

class Calculadora {
    protected double x;
    protected double y;

    Calculadora(double x, double y) {
        this.x = x;
        this.y = y;
    }
    double soma() {
        return x + y;
    }
    double subtracao() {
        return x - y;
    }
    double multiplicacao() {
        return x * y;
    }
    double divisao() {
        return x / y;
    }
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

I did not do an abstract to make the test easier, but that does not change anything. I have my doubts if you need this. I actually see little use for this class.

I've taken the class request because it's different responsibilities. Whoever takes care of the interaction with the user should not be the business class. I used a builder that is the right one to do.

If you already have the data you do not have to go to the methods as an argument. Every method that is not static already has a parameter that is this , so the values of the object are already accessible in all its methods. And this does not even need to be typed when the name is not ambiguous .

I pretty much did everything that was described in the question. And I gave better names and cleaner formatting.

    
10.11.2017 / 14:23