Calculator in Java

0

I have a little doubt about a graphing calculator that I'm doing in java. What happens is that I have everything done, but there is a problem pressing the same button and operate all the numbers. Then I leave the code:

    private void igualActionPerformed(java.awt.event.ActionEvent evt) {                                      
    Double num = Double.parseDouble(pantalla.getText().substring(aux,pantalla.getText().length()));
    numeros.add(num);
    int iterador = -1;
    for (int i = 0; i <= operadores.size() - 1; i++) {
        switch(operadores.get(i)){
            case '+':
                resultado = resultado + (numeros.get(0) + numeros.get(1));
            case '-':
                resultado = resultado - numeros.get(iterador+1);
            case '*':
                resultado = resultado * numeros.get(iterador+1);
            case '/':
                resultado = resultado / numeros.get(iterador+1);
            iterador++;
        }        
     System.out.println(resultado);   
     System.out.println(numeros.get(0) + numeros.get(1));
    }  
}               

As you can see, inside the for all the operations process is done, the point is that if you set, inside the case for addition, I keep the result of adding the index 0 and 1 of the ArrayList numbers in a variable called " result ".

The problem is that I print it, and then I print the direct sum and I get two totally different results, then I leave what the console prints:

run:
10.0
20.0
    
asked by Cristian Cubillos 19.07.2018 в 03:57
source

1 answer

1

It happens that since the result variable is in memory, the value that will print will be from the last operation that was done in the switch, I say this, because I do not know what the order is that the operators list handles.

One solution for you to know which values it takes "result" is that you make impressions for each case something like this:

resultado = resultado + (numeros.get(0) + numeros.get(1));
System.out.println("Resultado: " + resultado);
break;

Always remember to do a break; this does not let you enter another different case, that's where your result variable also changes. If it enters to add, it will immediately go to subtract, multiply, divide, then it will just do another iteration.

I hope I have helped you in the least.

    
answered by 19.07.2018 / 05:31
source