Home > database >  Android Studio Calculator
Android Studio Calculator

Time:12-13

Here is my Code for Calculator

But when the C button is pressed the last character of the equation window

gets changed to C which should not occur.

Please help me to get the code correct The image shows the emulator

    @Override
    public void onClick(View view) {
        MaterialButton button = (MaterialButton) view;
        String buttonText = button.getText().toString();
        String dataToCalculate = equation.getText().toString();

        if(buttonText.equals("AC")){
            equation.setText("");
            result.setText("0");
            return;
        }
        if(buttonText.equals("C")) {
            dataToCalculate = dataToCalculate.substring(0, dataToCalculate.length() - 1);
        }
        if(buttonText.equals("=")){
            equation.setText(result.getText());
            return;
        }else{
            dataToCalculate = dataToCalculate   buttonText;
        }
        equation.setText(dataToCalculate);

        String finalResult = getReasult(dataToCalculate);

        if(!finalResult.equals("ERROR")){
            result.setText(finalResult);
        }
    }

I have no idea why the letter C is getting printed.

please help me configure the code

CodePudding user response:

Your code enters first condition if(buttonText.equals("C")) , which is fine and works as excepted.

Next statement is again if statement with else case , and code tries to execute the same.(below code is executed).

if(buttonText.equals("=")){
    equation.setText(result.getText());
    return;
}else{
    dataToCalculate = dataToCalculate   buttonText;
}

dataToCalculate = dataToCalculate buttonText; this line adds the char C to your text.

Use else if or switch to handle this, or add return in if case (if(buttonText.equals("C"))) as you have done for other if conditions.

Use debugger, you will get better idea what's happening.

  • Related