Calculator error created in android studio

1

I started doing some things with in android studio. The error you are giving is in a simple calculator and does not do the correct operations, for example: 1 + 2 = 1,1 + 8 = 1, and others that are giving 0.
I have two textview , operation and result, and 16 buttons including numbers and the four operations. They all appear in the application, and when I click I get all the signals, only the operations that come out incorrect.

Follow the calculator code:

package com.example.familia.isabellyemmanuelly;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class Calculadora extends Activity {

    TextView textOperacao;
    TextView textResultado;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculadora);

        textOperacao = (TextView) findViewById(R.id.text_operacao);
        textOperacao.setText("");

        textResultado = (TextView) findViewById(R.id.text_resultado);
        textResultado.setText("");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.calculadora, menu);
        return true;
    }

    public void clickOne(View view){

        textOperacao.append("1");
    }

    public void clickTwo(View view){

        textOperacao.append("2");
    }

    public void clickThree(View view){

        textOperacao.append("3");
    }

    public void clickFour(View view){

        textOperacao.append("4");
    }

    public void clickFive(View view){

        textOperacao.append("5");
    }

    public void clickSix(View view){

        textOperacao.append("6");
    }

    public void clickSeven(View view){

        textOperacao.append("7");
    }

    public void clickEight(View view){

        textOperacao.append("8");
    }

    public void clickNine(View view){

        textOperacao.append("9");
    }

    public void clickZero(View view){

        textOperacao.append("0");
    }

    public void clickSum(View view){

        textOperacao.append(" + " );
    }

    public void clickSubtract(View view){

        textOperacao.append(" - ");
    }

    public void clickMultiply(View view){

        textOperacao.append(" x ");
    }

    public void clickDivide(View view){

        textOperacao.append(" / ");
    }

    public void clickC(View view){

        textOperacao.setText("");
        textResultado.setText("");
    }

    public void clickResult(View view){

        String operation = textOperacao.getText().toString();
        String[] components = operation.split(" ");

        if(components.length == 3) {

            double numero1 = (double) Integer.parseInt(components[0]);
            String sinal = components[1];
            double numero2 = (double) Integer.parseInt(components[2]);

            if(sinal.equals("+"))
                textResultado.setText( String.format("%.0f", (numero1 + numero2)) );

            if(sinal.equals("-"))
                textResultado.setText( String.format("%.0f", (numero1 - numero2)) );

            if(sinal.equals("x"))
                textResultado.setText( String.format("%.0f", (numero1 * numero2)) );

            if(sinal.equals("/")) {

                if( numero1 % numero2 != 0 )
                    textResultado.setText( String.format("%.2f", (numero1 / numero2)) );
                else textResultado.setText( String.format("%.0f", (numero1 / numero2)) );
            }
        }
        else textResultado.setText( "Operação não reconhecida :(" );
    }

}
    
asked by anonymous 19.06.2016 / 08:47

1 answer

1

First of all I would not implement a calculator like you are doing. It would use two cells one for operands and one for operators and, manipulating these two cells, would have more performative results than "parse" strings to take operations.

If you decide to continue to implement this template, in your clickResult, call this method, passing the entire string, similar to the one you display on the display to the user. This code is available and has been quoted here

public static double eval(final String str) {
    return new Object() {
        int pos = -1, ch;

        void nextChar() {
            ch = (++pos < str.length()) ? str.charAt(pos) : -1;
        }

        boolean eat(int charToEat) {
            while (ch == ' ') nextChar();
            if (ch == charToEat) {
                nextChar();
                return true;
            }
            return false;
        }

        double parse() {
            nextChar();
            double x = parseExpression();
            if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
            return x;
        }

        // Grammar:
        // expression = term | expression '+' term | expression '-' term
        // term = factor | term '*' factor | term '/' factor
        // factor = '+' factor | '-' factor | '(' expression ')'
        //        | number | functionName factor | factor '^' factor

        double parseExpression() {
            double x = parseTerm();
            for (;;) {
                if      (eat('+')) x += parseTerm(); // addition
                else if (eat('-')) x -= parseTerm(); // subtraction
                else return x;
            }
        }

        double parseTerm() {
            double x = parseFactor();
            for (;;) {
                if      (eat('*')) x *= parseFactor(); // multiplication
                else if (eat('/')) x /= parseFactor(); // division
                else return x;
            }
        }

        double parseFactor() {
            if (eat('+')) return parseFactor(); // unary plus
            if (eat('-')) return -parseFactor(); // unary minus

            double x;
            int startPos = this.pos;
            if (eat('(')) { // parentheses
                x = parseExpression();
                eat(')');
            } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
                while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                x = Double.parseDouble(str.substring(startPos, this.pos));
            } else if (ch >= 'a' && ch <= 'z') { // functions
                while (ch >= 'a' && ch <= 'z') nextChar();
                String func = str.substring(startPos, this.pos);
                x = parseFactor();
                if (func.equals("sqrt")) x = Math.sqrt(x);
                else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
                else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
                else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
                else throw new RuntimeException("Unknown function: " + func);
            } else {
                throw new RuntimeException("Unexpected: " + (char)ch);
            }

            if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation

            return x;
        }
    }.parse();
}
    
22.06.2016 / 18:07