当我按“计算”按钮应用程序时崩溃
@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");
}
最佳答案
以下解决方案在输入不包含有效浮点的情况下处理空字符串和无效输入。
@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");
}
}
关于java - 当数字和百分比窗口为空时,百分比计算器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321111/