当我按下计算按钮应用程序时崩溃
@Override
public void onClick(View view) {
if (percentageTxt.getText()!=null && numberTxt.getText()!=null){
float percentege = Float.parseFloat(percentageTxt.getText().toString());
float dec = percentege / 100;
float total = dec * Float.parseFloat(numberTxt.getText().toString());
totalTextWiew.setText(Float.toString(total));
}else{
totalTextWiew.setText("Error");
}
答案 0 :(得分:1)
以下解决方案处理空字符串,并在输入不包含有效浮点数时处理无效输入。
@Override
public void onClick(View view) {
try {
float percentege = Float.parseFloat(percentageTxt.getText().toString());
float dec = percentege / 100;
float total = dec * Float.parseFloat(numberTxt.getText().toString());
totalTextWiew.setText(Float.toString(total));
} catch (NumberFormatException nfe) {
totalTextWiew.setText("Error");
}
}