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 に答える