简单的计算器不工作

时间:2016-08-04 21:52:34

标签: java android listener

有人能告诉我下面的听众有什么问题吗?我总是崩溃......

@Override
public void onClick(View view) {
    Editable num1 = NumberOne.getText();
    Editable num2 = NumberTwo.getText();
    int um1 = Integer.parseInt(num1.toString());
    int um2 = Integer.parseInt(num2.toString());
    Results.setText(um1 + um2);
}

2 个答案:

答案 0 :(得分:2)

setText方法接受String作为参数。 um1 + um2的结果将是整数。我建议你先将结果转换为String,然后在setText方法中设置它。

这样的事情应该有效:

Results.setText(Integer.toString(um1+um2));

你可以做得更好:

Results.setText(Integer.toString(Integer.parseInt(num1.toString()) + Integer.parseInt(num2.toString())));

答案 1 :(得分:1)

它不起作用的原因是因为您无法将文本设置为。你必须使用Results.setText(String.valueOf(um1 + um2))(如Andre所说)将整数转换为字符串。因此,setText将起作用。