textview中的Android基础数学

时间:2014-02-04 20:45:12

标签: android

我正在尝试添加两个数字,并使用此代码在textview中显示它们。这里的问题是它不添加数字,它只显示整个字符串。

CharSequence fnum, snum, symbol;
final TextView CalTextBox = (TextView) findViewById(R.id.MainTextview);
symbol = "+"; // addition selected
fnum = CalTextBox.getText(); // store number into fnum 
snum = CalTextBox.getText(); //new number will be added in the code and be stored into snum
CalTextBox.setText(""); // delete whats in the text box
CalTextBox.setText(snum + "" + symbol + "" + fnum); // add two numbers

3 个答案:

答案 0 :(得分:3)

好吧,'+'运算符在字符串上使用时会执行连接(就像在这种情况下一样)。要执行数学运算,必须先将它们转换为数字。我想你可以用这个:

// Convert the 2 String to integer values
int first = Integer.valueOf(fnum);
int second = Integer.valueOf(snum);

// Compute the sum
int sum = first + second;

// Create the String you can use to display in the TextView
String textToDisplay = String.valueOf(sum);

答案 1 :(得分:1)

对于数学运算,最好使用int,long或double变量类型。而不是CharSequence使用例如int。

integer (int)使用String (text)使用

int fnum, snum, symbol;
int fnum = Integer.parseInt("10"); or
fnum = Integer.parseInt(CalTextBox.getText());
CalTextBox.setText("" + (snum + symbol + fnum));

答案 2 :(得分:1)

snum = "2";
fnum = "3";
symbol = "+";

snum + "" + symbol + "" + fnum  =  "2+3"

相反,你应该将String转换为整数或双精度并进行适当的控制,如null或空,或非数字,然后,

int result = Integer.parseInt(snum) + Integer.parseInt(fnum);

CalTextBox.setText("" + result);