简体   繁体   English

编辑文字未返回负值

[英]Edit text not returning negative value

I'm calling this method in my android app: 我在我的android应用程序中调用此方法:

public void Subtraction() {
    text.setText("");
    long total = num1 - num2;
    text.setText(Long.toString(total));
}

Now, when I calculate say 15-20, i don't get -5, but rather I get 0. 现在,当我计算出15-20时,我没有得到-5,而是得到了0。

num1 and num2 are declared as longs. num1和num2声明为long。

Does anyone know why? 有人知道为什么吗?

Thanks for your time! 谢谢你的时间!

EDIT: I'm getting num1 and num2 from user input in the text field : 编辑:我从文本字段中的用户输入获取num1和num2:

// Subtraction case
        case R.id.buttonsubtract:
            division = false;
            addition = false;
            multiply = false;

            num1 = Long.parseLong(text.getText().toString());
            num2 = Long.parseLong(text.getText().toString());
            text.setText(text.getText() + "-");
            subtraction = true;
            break;

The reason your value is 0 is because both num1 & num2 are being fetched from the same text field ' text ' Hence they have the same value. 您的值为0的原因是因为num1和num2都从同一文本字段' text '中获取,因此它们具有相同的值。

So say if user entered a value 4 in EditText field text then num1 & num2 will have the same value. 假设如果用户在EditText字段text输入值4,则num1和num2将具有相同的值。

If you have separate text fields for user to enter num1 & num2 , then you should read values from those separate EditText fields. 如果您有单独的文本字段供用户输入num1和num2,则应从这些单独的EditText字段中读取值。

If you want to use only one text field, there are multiple ways to handle it, one simple way is as follows (I am assuming you are working on long values only) : 如果只想使用一个文本字段,则有多种处理方式,一种简单的方式如下(我假设您仅在处理长值):

1) Initialize a class variable long leftOperand = 0; 1)初始化一个类变量long leftOperand = 0; 2) When user click on + , _ , * , / then put the value of the variable in text field in the variable leftOperand . 2)当用户单击+,_,*和/时,然后将变量的值放在变量leftOperand的文本字段中。

 leftOperand  = Long.parseLong(text.getText().toString());

Also store the operation that user wants to perform (say in the form of an enum). 还存储用户想要执行的操作(例如枚举形式)。

3) Now when user presses '=' then just compute the value long newValue = Long.parseLong(text.getText().toString()); 3)现在,当用户按下“ =”时,只需计算long newValue = Long.parseLong(text.getText()。toString())的值即可;

long output = leftOperand   (operation) newValue ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM