Error in calculator created in android studio

Asked

Viewed 442 times

1

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

Follow the code of the calculator:

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 :(" );
    }

}
  • 1

    Post the snippet of code that captures the numbers and does the operations, before they start to negate your question for lack of content and so we know what is wrong.

  • I put the code there, Brother

  • buttons are 2 mediumtextview for result and operation 1-9 and operators " + ", " - ", " * ", " / "

  • Try using String.valueOf(numero1 + numero2) to extract the result from the sum operation, same for other operations

  • if(Components.length == 3) { double numero1 = (double) Integer.parseint(Components[0]); String signal = Components[1]; double numero2 = (double) Integer.parseint(Components[2]); did so and it worked .... vlw Irmao___________________________________________________ double numero1 = Double.valueOf(Components[0]). doubleValue(); String signal = Components[1]; double numero2 = Double.valueOf(Components[2]). doubleValue();

1 answer

1

First of all, I wouldn’t implement a calculator like you’re doing. It would use two stacks one for operands and the other for operators and, manipulating these two stacks, would have the results more performative than "parsing" strings to take operations.

If you decide to continue to implement in this model, in your clickResult, call this method, passing the entire string, similar to the one you show in the display for the user. This code is available and has been cited 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();
}

Browser other questions tagged

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