2011-09-03 54 views
1

尊重所有;使用异常android系统

我是新来编程,并找到一个障碍即单击按钮时没有在EDITTEXT箱被输入任何东西转换矿活动崩溃。

所以研究后,我得到了尝试和捕获方法和它的作品好。

 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(); 
     }} 

但主要的问题是,我在所有按钮的方法来使用它。 有没有其他的方式来避免这种代码重复。

请帮助..

+0

什么是要价较高的错误? –

+0

对不起,我是Android新手,所以我不知道如何使用locat ...请提供初步的知识。 –

+0

窗口>显示视图>其他 然后展开Android,然后选择LogCat –

回答

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(); 
    }} 
+0

谢谢:)非常感谢你 –