当数字和百分比窗口为空时,百分比计算器崩溃

时间:2016-10-29 16:19:13

标签: java android crash calculator

当我按下计算按钮应用程序时崩溃

            @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");
                }

1 个答案:

答案 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");
        }
    }