Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
textview中的Android基础数学_Android - Fatal编程技术网

textview中的Android基础数学

textview中的Android基础数学,android,Android,我正在尝试添加两个数字,并使用此代码在textview中显示它们。这里的问题是,它不添加数字,只显示整个字符串 CharSequence fnum, snum, symbol; final TextView CalTextBox = (TextView) findViewById(R.id.MainTextview); symbol = "+"; // addition selected fnum = CalTextBox.getText(); // store number into fnum

我正在尝试添加两个数字,并使用此代码在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

如果在字符串上使用“+”运算符,则会执行串联(如本例所示)。要执行数学运算,必须先将它们转换为数字。我想你可以用这个:

// 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);

如果在字符串上使用“+”运算符,则会执行串联(如本例所示)。要执行数学运算,必须先将它们转换为数字。我想你可以用这个:

// 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);

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

要从
字符串(文本)
获取
整数(int)
,请使用:

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

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

要从
字符串(文本)
获取
整数(int)
,请使用:

int fnum, snum, symbol;
int fnum = Integer.parseInt("10"); or
fnum = Integer.parseInt(CalTextBox.getText());
CalTextBox.setText("" + (snum + symbol + fnum));
相反,您应该将字符串转换为整数或双精度,并设置适当的控件,如null或empty,或非数值

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

CalTextBox.setText("" + result);
相反,您应该将字符串转换为整数或双精度,并设置适当的控件,如null或empty,或非数值

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

CalTextBox.setText("" + result);

我只是好奇:通过Integer.parseInt还是Integer.valueOf得到int值有什么区别吗?parseInt返回primitive int,valueOf返回Integer object我只是好奇:通过Integer.parseInt还是Integer.valueOf得到int值有什么区别吗?parseInt返回primitive int,valueOf返回整数对象