所以如果我有值 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));
}
}