Android: Division and subtraction always equal 1.0

I’m making a simple calculator but when I try to divide I always get 1.0 and when I subtract I always get zero. Addition and multiplication work fine.

I’ve read similar questions such as : Why does integer division code give the wrong answer? Dividing two integers in Java gives me 0 or 100? Division in Java always results in zero (0)?

and many more…

Here is a part of my code :

 if (minu) {
    number1 = Double.valueOf(display1.getText().toString());
    number2 = Double.valueOf(display1.getText().toString());

    display1.setText("");
    display2.setText("");
    displaySymbol.setText("");

    answer = number1 - number2;

    display1.setText(Double.toString(answer));
 }

and the division:

if (divid) {
    number1 = Double.valueOf(display1.getText().toString());
    number2 = Double.valueOf(display1.getText().toString());

    display1.setText("");
    display2.setText("");
    displaySymbol.setText("");

    answer = number2  / number1;

    display1.setText(Double.toString(answer));
}

Please help!

Answer

You are reading the value from display1 twice, you forgot to change the reading of number2 to display2.


Replace:

number2 = Double.valueOf(display1.getText().toString());

with

number2 = Double.valueOf(display2.getText().toString());

Your function would end up being:

if(minu){
    number1 = Double.valueOf(display1.getText().toString());
    number2 = Double.valueOf(display2.getText().toString());

    display1.setText("");
    display2.setText("");
    displaySymbol.setText("");

    answer = number1 - number2;

    display1.setText(Double.toString(answer));
}

Leave a Reply

Your email address will not be published. Required fields are marked *