ArithmeticException-catch子句不显示预期的文本

时间:2019-07-03 04:31:40

标签: java android-studio

在下面的代码中,我使用了ArithmeticException异常,并且我想在catch子句中以如下方式处理它:显示无法被0除的消息,但是当我尝试将其除以0时,上述内容消息未显示,但是:“ Divide = Infinity”。

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        float x, y, Result = 0;
        String item = "Do not divide by 0";

        if(radioButton.isChecked()){

            try {

                x = Float.parseFloat(editText.getText().toString());
                y = Float.parseFloat(editText2.getText().toString());

                Result = x/y;
                textView.setText("Divide = " + Float.toString(Result));


            } catch(ArithmeticException e) {

                textView.setText(item);
            }


        }

        else if(radioButton2.isChecked()){

            x = Float.parseFloat(editText.getText().toString());
            y = Float.parseFloat(editText2.getText().toString());

            Result = x * y;
            textView.setText("Multiplication = " + Float.toString(Result));
        }

        else if (radioButton3.isChecked()) {

            x = Float.parseFloat(editText.getText().toString());
            y = Float.parseFloat(editText2.getText().toString());
            Result = x - y;
            textView.setText("Subtract = " + Float.toString(Result));
        }

        else {

            x = Float.parseFloat(editText.getText().toString());
            y = Float.parseFloat(editText2.getText().toString());
            Result = x + y;
            textView.setText("Addition = " + Float.toString(Result));
        }


    }
});

我该怎么做才能在TextView中显示符合我期望的文本?

0 个答案:

没有答案