【发布时间】:2014-06-12 19:30:05
【问题描述】:
所以如果我的值是 1234,那么输出应该是 4。
我已经编写了以下代码,但不知道我做错了什么。 这是一个应用程序,它添加了两个数字。所以我有两个 EditTextfields。但如果 EditTextfield 留空,应用程序就会崩溃。 所以我想将值 0 分配给 EditTextfield,该字段已留空,因为它(应该)具有 0 的字符长度。
这应该会得到正确的结果:
例如,如果 EditTextfield "firstnumET" 的值为 5 并且 "secondnumET" 为空:
5 + 0 = 5
问题可能是
private int firstnum;
private int secondnum;
private int total;
EditText firstnumET;
EditText secondnumET;
TextView ansTV;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cal2_numbers);
firstnumET = (EditText) findViewById(R.id.edittxt1);
secondnumET = (EditText) findViewById(R.id.edittxt2);
ansTV = (TextView) findViewById(R.id.ans);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new ClickButton());
}
private class ClickButton implements Button.OnClickListener {
@Override
public void onClick(View v) {
firstnum = Integer.parseInt(firstnumET.getText().toString());
secondnum = Integer.parseInt(secondnumET.getText().toString());
int cache1 = Integer.toString(firstnum).length();
int cache2 = Integer.toString(secondnum).length();
if (cache1 == 0) {
ansTV.setText(Integer.toString(secondnum));
}
if (cache2 == 0) {
ansTV.setText(Integer.toString(firstnum));
}
total = firstnum + secondnum;
ansTV.setText(Integer.toString(total));
}
}
【问题讨论】:
标签: android onclicklistener variable-length