1

尊重所有人;

我是编程新手,发现一个障碍,即单击按钮而没有在 Edittext 框中输入任何内容会将我的活动转换为崩溃。

因此,经过研究,我得到了 Try and catch 方法,效果很好。

     public void clickDiv(View button){
     try{
         EditText Input = (EditText) findViewById(R.id.editext);

        String input = Input.getText().toString();

         String empty = "";

         Float floatInput = new Float (input);

         TextView TextShow = (TextView) findViewById(R.id.textView1);

         String Newinput = floatInput.toString();

         TextShow.setText(Newinput);

         if (answer == 0){

             answer =  (answer+1) / floatInput  ;
         }else{
             answer =  (answer) / floatInput  ;
         }
         String answerString = answer.toString();

         TextShow.setText(answerString);

         Input.setText(empty); }
         catch (Exception e) {
         AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(this).create();
          alertDialog.setMessage("Could not find the operand");
         alertDialog.show();
      }}

但主要问题是我必须在所有按钮方法中使用它。还有其他方法可以避免代码中的这种重复。

请帮忙..

4

1 回答 1

0

像这样修改代码。希望它可以帮助你。

public void clickDiv(View button){
 try{
     EditText Input = (EditText) findViewById(R.id.editext);

    String input = Input.getText().toString();

     //if no input, set the error to the edittext and return
     if(input.trim().length()==0){
        Input.setError("An input is required");
        return;
     }
     String empty = "";

     Float floatInput = new Float (input);

     TextView TextShow = (TextView) findViewById(R.id.textView1);

     String Newinput = floatInput.toString();

     TextShow.setText(Newinput);

     if (answer == 0){

         answer =  (answer+1) / floatInput  ;
     }else{
         answer =  (answer) / floatInput  ;
     }
     String answerString = answer.toString();

     TextShow.setText(answerString);

     Input.setText(empty); }
     catch (Exception e) {
     AlertDialog alertDialog;
    alertDialog = new AlertDialog.Builder(this).create();
      alertDialog.setMessage("Could not find the operand");
     alertDialog.show();
  }}
于 2011-09-03T07:48:01.523 回答