我正在尝试构建一个提示计算。 这是我的代码的一部分:
public void onTextChanged(CharSequence s, int start, int before, int count) {
double billAmount = Double.parseDouble(s.toString());
tip10EditText.setText("" + billAmount * .1);
tip15EditText.setText("" + billAmount * .15);
tip20EditText.setText("" + billAmount * .2);
total10EditText.setText("" + (billAmount + billAmount * 0.1));
total15EditText.setText("" + (billAmount + billAmount * 0.15));
total20EditText.setText("" + (billAmount + billAmount * 0.2));
}
问题是,当我从帐单编辑文本中删除所有内容时,应用程序崩溃了.. 我的朋友找到了解决问题的方法。这是他的代码:
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals("")) {
bill = Double.parseDouble(s.toString());
tip10EditText.setText((bill / 10) + "");
total10EditText.setText((bill + (bill / 10)) + "");
// the String.format("%.2f", is to SHORTEN the tail of the double to 2 digits
tip15EditText.setText(String.format("%.2f", (bill / 6.6666) ));
total15EditText.setText(String.format("%.2f",(bill + (bill / 6.6666)) ));
tip20EditText.setText(String.format("%.2f", (bill / 5) ));
total20EditText.setText(String.format("%.2f",(bill + (bill / 5)) ));
// to handle the seekBar changing according to the bill
double billCu = Double.parseDouble(billEditText.getText().toString());
// total20EditText.setText(String.format("%.2f",(tipOf ));
double progressPer=Double.parseDouble(customTipTextView.getText().toString());
double tipOf = (billCu/100)*progressPer;
tipCustomEditText.setText(String.format("%.2f",(tipOf )));
totalCustomEditText.setText(String.format("%.2f",((billCu+tipOf) )));
}
else {
tip10EditText.setText( "");
total10EditText.setText( "");
tip15EditText.setText( "");
total15EditText.setText( "");
tip20EditText.setText( "");
total20EditText.setText( "");
tipCustomEditText.setText("");
totalCustomEditText.setText("");
}
}
有没有更好的方法来解决这个问题?
答案 0 :(得分:2)
public void onTextChanged(CharSequence s, int start, int before, int count) {
double billAmount = 0.0;
if(s.length() != 0){
billAmount = Double.parseDouble(s.toString());
}
tip10EditText.setText("" + billAmount * .1);
tip15EditText.setText("" + billAmount * .15);
tip20EditText.setText("" + billAmount * .2);
total10EditText.setText("" + (billAmount + billAmount * 0.1));
total15EditText.setText("" + (billAmount + billAmount * 0.15));
total20EditText.setText("" + (billAmount + billAmount * 0.2));
}
仅当文本框中存在的任何输入显示为0时,上述代码才会计算正确的值。
答案 1 :(得分:0)
试试这个:
if (!TextUtils.isEmpty(s)) {
Then do your stuff....
}
答案 2 :(得分:0)
将您的代码放在以下if语句中:
if (s.length() > 0)
答案 3 :(得分:0)
在catch块中使用带有NumberFormatException的try catch块,并且通过使用它,你也可以处理错误的输入类型。
try{
//your code
}catch(NumberFormatException npe){
//handle the exception and intimate the user if needed.
}catch(Exception e){
}