-1

当我单击程序中的按钮而不输入数据时,它会同时显示两个错误(我在下面的程序中突出显示)。在这里,我一次只需要得到一个错误,我的意思是当它为空时,它显示适当的一个。反之亦然..

b.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if(v==findViewById(R.id.button1)) {
        et1 = (EditText) findViewById(R.id.editText1);
        if(et1.getText()!=null ) {
        try {
                radius = Double.valueOf(et1.getText().toString());
        }
        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
        }
        }

        if(radius==0.0) {
            Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
        }
        try {
            output = (double) Math.round(Math.PI * radius * radius);
            String s = Double.toString(output);
            tv1.setText(s);
        }
        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
        }
        }
    }
});
4

1 回答 1

1

do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:

  b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {

            case R.id.button1:
                Pattern p = Pattern.compile("([0-9]*)");

                if (et1.getText().toString().trim().length() > 0) {
                    Matcher m = p.matcher(et1.getText().toString().trim());

                    if (m.matches()) {
                        radius = Double.valueOf(et1.getText().toString());
                        output = (double) Math.round(Math.PI * radius
                                * radius);
                        tv1.setText(Double.toString(output));
                    } else
                        Toast.makeText(getApplicationContext(),
                                "incorrect value", Toast.LENGTH_SHORT)
                                .show();
                } else
                    Toast.makeText(getApplicationContext(),
                            "input is empty", Toast.LENGTH_SHORT).show();

                break;

            default:
            }

        }
    });

In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.

BTW, using switch-case is a better approach for click listeners

于 2013-02-06T15:42:51.217 回答