2014-06-09 64 views
-4

我想总结两个EditText中输入的数字,然后当按钮被点击时,我想总和显示在第三个EditText,但它似乎有什么错误。总结两个edittext并得到第三个结果

这是我的代码:

result = (Button)findViewById(R.id.btn1); 
    nb1 = (EditText)findViewById(R.id.nb1); 
    nb2 = (EditText)findViewById(R.id.nb2); 
    nb3 = (EditText)findViewById(R.id.nb3); 


    } 

    public void result (View v){ 
     String n1 = nb1.getText().toString(); 
     int n11 = Integer.parseInt(n1); 

     String n2 = nb2.getText().toString(); 
     int n22 = Integer.parseInt(n2); 


     nb3.setText(n11 + n22); 
+0

检查我的回答如下。 – Aniruddha

回答

2

更改此

nb3.setText(n11 + n22); 

nb3.setText(String.valueOf(n11 + n22)); 
0

地说:

nb3.setText("" + n11 + n22); 
3

使用以下代码。

nb3.setText(String.valueOf(n11 + n22)); 
2

变化:

nb3.setText(n11 + n22); 

nb3.setText(String.valueOf(n11 + n22)); 

的setText把整数作为这就是为什么你需要明确地将其转换为一个字符串资源ID。

0

如果在没有在edittext中输入值的情况下按下按钮,它将显示NumberFormatException。所以,做这样的

public void result (View v){ 

try 
{ 
     int sum = 0; 
     String n1 = nb1.getText().toString(); 
     int n11 = Integer.parseInt(n1); 

     String n2 = nb2.getText().toString(); 
     int n22 = Integer.parseInt(n2); 
     sum = n11 + n22; 

     nb3.setText("Sum is = " + sum); // nb3.setText(" " + sum); if you don't want only result to be displayed. 
} 
catch (Exception e) 
{ 

} 
} 
+0

谢谢,先生,它的工作原理 –

0

执行以下操作:

int num1 = Integer.parseInt(edit1.getText().toString()); 
int num2 = Integer.parseInt(edit2.getText().toString()); 

edit3.setText(String.valueOf(num1+num2));//this you need to do 
相关问题