Calculator doing operations on the result of a previous operation

Asked

Viewed 343 times

0

In my Java class we are learning object orientation, and my prof. asked for a calculator. In this calculator, the user will type the entire expression, for example 10+10, and the algorithm needs to recognize which expression is running and display the result on the screen, i.e., 10+10 = 20. So far I’ve done and delivered.

However, he asked us to complement this calculator, so that after the display of the result 10+10 = 20, the user type, for example, +10, and the result will then be 30. If the user reports other operations they need to "aggregate" the result as well.

public class Calc {

public int som(int num1, int num2) {

    return num1 + num2;

}
public int sub(int num1, int num2){

    return num1 - num2;

}
public int div(int num1,int num2){

    return num1 / num2;

}
public int mult(int num1, int num2){

    return num1 - num2;

}



public static void main (String args[]){

    //criando um objeto c a apartir do metodo calc
    Calc c = new Calc();

    //declarando as varíaveis
    int opcao = 5;
    int num1;
    int num2;

      Scanner input = new Scanner(System.in);  


    System.out.println("-Escolha uma opção-");
    System.out.println("1. Soma");  
    System.out.println("2. Subtracao");  
    System.out.println("3. Multiplicacao");  
    System.out.println("4. Divisao");  
    System.out.println("0. Sair");  
    System.out.println("Operação: ");  

    opcao = input.nextInt();

    while (opcao != 0) {


        if (opcao == 1) {



            Scanner input1 = new Scanner(System.in);  

            System.out.println("Qual o primeiro numero: ");
             num1 = input1.nextInt();
            System.out.println("Qual o segundo numero: ");
             num2 = input1.nextInt();

             /***/
                int operacao = c.som(num1, num2);

                System.out.println(operacao);
            break;
        }
  • Welcome! You know how to use Static variables? What is the use of a static or final variable in java? I believe that there is the secret, more the night I can look at your code calmly, for now the tip I give is to try to put Static in any of the 3 variables: private Double valorCalculado;
private Double valorUm;
private Double valorDois;

1 answer

1

If you want the calculator to accept expressions like "+10" that add 10 to the current result, then the Calculadora should store the current output internally, and the executed operations should operate on this current output. So it would look something like:

public class Calculadora {

    private int resultadoAtual = 0;

    public int calcular(String expressao) {
        // separar a expressão por espaços
        String[] tokens = expressao.split(" ");
        if (tokens.length == 3) { // 3 partes (um número, operação, outro número)
            int op1 = Integer.parseInt(tokens[0]);
            int op2 = Integer.parseInt(tokens[2]);
            this.executaOperacao(op1, op2, tokens[1].charAt(0));
        } else if (tokens.length == 1) { // 1 parte (casos como "+10")
            int op = Integer.parseInt(tokens[0].substring(1));
            this.executaOperacao(this.resultadoAtual, op, tokens[0].charAt(0));
        } else {
            System.out.println("Expressão não reconhecida");
        }

        return resultadoAtual;
    }

    private void executaOperacao(int op1, int op2, char op) {
        switch (op) {
            case '+':
                this.resultadoAtual = op1 + op2;
                break;
            case '-':
                this.resultadoAtual = op1 - op2;
                break;
            case '*':
                this.resultadoAtual = op1 * op2;
                break;
            case '/':
                this.resultadoAtual = op1 / op2;
                break;
        }
    }

    public void limpar() {
        this.resultadoAtual = 0;
    }
}

I created the field resultadoAtual which will be used to store the current result of the calculator. The method calcular receives a String containing the expression, and as it is an exercise, I am assuming some premises:

  • expressions with two operands (such as "10 + 20" or "5 * 12") always have spaces separating their parts (ie, could not be "10+20" - although it is possible, see an option at the end)
  • expressions that "add" to the current result (such as "+10" or "*30") no spaces between operation and number
  • the code assumes that Integer.parseInt always receives a valid integer number (I am not treating the exceptions)
  • operations are always done in integer numbers, so the result of 11 / 4 will be 2 (Java rounds when operands are int) - anyway, if you have "3.2" in the expression, will give error, as the previous item

In short, the code does not make more complex validations in the typed expression (in a real system it would do this, but it is quite complicated to accept any valid numerical expression, and I believe it already evades the scope of the exercise).

Finally, the method calcular assumes all the above premises and makes the calculation, storing the result in resultadoAtual (and this is saved, so it can be "aggregated" in future operations). In general, the calculator works like this:

  • if typed 10 + 20, the resultadoAtual will be 30
  • then if typed +5, the resultadoAtual becomes 35
  • if another expression, such as 1 + 2, the resultadoAtual becomes 3 (this is a complete expression, which does not "add" to the current result, so I understand that the previous value should be overwritten)
  • and so on...

Also included an option to "clear" the current result and set it to zero (more or less like the key C of calculators).

And I did so (reading the whole expression) because you said that the user will "type the entire expression" (i.e., "10 + 20", instead of typing each part separately as you did). A way to use the calculator would be:

public static void main(String[] args) {
    Calculadora calc = new Calculadora();
    Scanner input = new Scanner(System.in);
    String expressao = "";
    while (true) {
        System.out.println("-Escolha uma opção-");
        System.out.println("Digitar uma expressão (ex: '10 + 20', ou simplesmente '+20')");
        System.out.println("'c' - Limpar o resultado atual");
        System.out.println("'q' - Sair");
        System.out.println("> ");
        expressao = input.nextLine();
        if ("q".equals(expressao)) {
            break; // sai do while
        }

        if ("c".equals(expressao)) {
            calc.limpar();
        } else {
            System.out.println(calc.calcular(expressao));
        }
    }
}

The while(true) is running indefinitely, allowing the user to type as many expressions as he wants. Typing q, he comes out of while.


Just as a curiosity (because I think it already escapes the scope of the exercise), to accept the expression without spaces ("10+20"), an option would be to use regular expressions (in the package java.util.regex):

public int calcular(String expressao) {
    Matcher matcher = Pattern.compile("(\\d+)?\\s*([-+*/])\\s*(\\d+)").matcher(expressao);
    if (matcher.find()) {
        int op1;
        if (matcher.group(1) == null) { // não tem o primeiro operando (é uma expressão do tipo "+10")
            op1 = this.resultadoAtual;
        } else {
            op1 = Integer.parseInt(matcher.group(1));
        }
        char op = matcher.group(2).charAt(0);
        int op2 = Integer.parseInt(matcher.group(3));
        this.executaOperacao(op1, op2, op);
    } else {
        System.out.println("Expressão inválida");
    }
}

There are other options too, but as it is an exercise, they probably want you to implement everything "at hand" even...

Browser other questions tagged

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